无法将类型'System.Collections.Generic.IEnumerable <anonymoustype#1>'隐式转换为'System.Collections.Generic.List <modelclass> </modelclass> </anonymoustype#1>

时间:2013-02-12 16:36:07

标签: c# linq linq-to-sql

我正在尝试填充AccountNumber不存在的交易数据。我需要访问Account表才能得到它。我收到以下错误,我试图返回IEnumerable

无法隐式将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;

    }

2 个答案:

答案 0 :(得分: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 :(得分:2)

您在Linq查询的“选择新”部分中投影的匿名类型无法直接投放到“交易”类型。

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

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();
相关问题