2013-02-12 145 views
5

我想填充AccountNumber不存在的Transaction数据。我需要访问帐户表来获取。我收到以下错误在那里我试图返回的IEnumerable无法将类型'System.Collections.Generic.IEnumerable <AnonymousType#1>'隐式转换为'System.Collections.Generic.List <modelClass>

不能隐式类型转换System.Collections.Generic.IEnumerable<AnonymousType#1>System.Collections.Generic.List<ProjectModel.Transaction>

错误显示在.ToList()的顶部;部分代码。我究竟做错了什么?

代码:

public static IEnumerable<Transaction>GetAllTransactions() 
    { 
     List<Transaction> allTransactions = new List<Transaction>(); 
     using (var context = new CostReportEntities()) 
     { 
      allTransactions = (from t in context.Transactions 
           join acc in context.Accounts on t.AccountID equals acc.AccountID 
           where t.AccountID == acc.AccountID 
           select new 
           { 
            acc.AccountNumber, 
            t.LocalAmount 
           }).ToList(); 

     } 
     return allTransactions; 

    } 

回答

5

匿名类型列表不能被转换为事务列表。看起来像你的Transaction类没有AccountNumber属性。你也不能从方法中返回匿名对象。所以,你应该创建一些类型将举行所需数据:

public class AccountTransaction 
{ 
    public int LocalAmount { get; set; } 
    public int AccountNumber { get; set; } 
} 

,并返回这些对象:

public static IEnumerable<AccountTransaction> GetAllTransactions() 
{  
    using (var context = new CostReportEntities()) 
    { 
     return (from t in context.Transactions 
       join acc in context.Accounts 
        on t.AccountID equals acc.AccountID    
       select new AccountTransaction { 
        AccountNumber = acc.AccountNumber, 
        LocalAmount = t.LocalAmount 
       }).ToList(); 
    } 
} 

BTW你不需要重复在过滤器

+1

这工作完美。优秀的答案。非常感谢让我走向正确的方向。做到这一点,我也学到了其他一些东西。现在我知道什么是ViewModel。 – shaz 2013-02-12 21:33:52

2

你正在你的LINQ查询的“选择新的”一节中突出不能直接铸造到你的“交易”类型的匿名类型。

相反,您应该投影一个新的事务实例。以下可能有所帮助:

allTransactions = (from t in context.Transactions 
    join acc in context.Accounts on t.AccountID equals acc.AccountID 
    where t.AccountID == acc.AccountID 
    select new Transaction() 
    { 
     AccountNumber = acc.AccountNumber, 
     LocalAmount = t.LocalAmount 
    }).ToList(); 
+0

连接条件,这将不起作用,因为我在Transaction表中没有AccountNumber属性。 – shaz 2013-02-12 21:34:53

+0

下次也许会列出您的poco课程的属性? :) – RainbowFish 2013-02-13 08:32:10

+0

这绝对是一个好主意,我一定会记得下次。感谢您的帮助。 – shaz 2013-02-13 08:57:36

相关问题