无法将类型’System.Collections.Generic.IEnumerable ‘隐式转换为’System.Collections.Generic.List
我正在尝试填充AccountNumber不存在的交易数据。 我需要访问Account表来获取它。 我收到以下错误,我试图返回IEnumerable
无法将类型System.Collections.Generic.IEnumerable
隐式转换为System.Collections.Generic.List
错误显示在.ToList(); 部分代码。 我究竟做错了什么?
代码是:
public static IEnumerableGetAllTransactions() { List allTransactions = new List(); 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; }
无法将匿名类型列表转换为事务列表。 看起来您的Transaction
类没有AccountNumber
属性。 此外,您无法从方法返回匿名对象。 所以你应该创建一些保存所需数据的类型:
public class AccountTransaction { public int LocalAmount { get; set; } public int AccountNumber { get; set; } }
并返回这些对象:
public static IEnumerable 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(); } }
顺便说一句,你不需要在filter的重复连接条件
您在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();