问题描述
我正在尝试填充 AccountNumber 不存在的交易数据.我需要访问 Account 表才能得到它.我在尝试返回 IEnumerable
I am trying to populate Transaction data where AccountNumber does not exist. I need to access the Account table to get that. I am getting the following error where I am trying to return IEnumerable
无法将类型System.Collections.Generic.IEnumerable
隐式转换为System.Collections.Generic.List
错误显示在代码的 .ToList(); 顶部.我究竟做错了什么?
The error is shown on top of .ToList(); part of the code. What am I doing wrong?
代码是:
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;
}
推荐答案
匿名类型列表不能转换为事务列表.看起来您的 Transaction
类没有 AccountNumber
属性.您也不能从方法返回匿名对象.所以你应该创建一些类型来保存所需的数据:
List of anonymous types cannot be casted to list of transactions. Looks like your Transaction
class do not have AccountNumber
property. Also you cannot return anonymous objects from methods. So you should create some type which will hold required data:
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();
}
}
顺便说一句在 where 过滤器中不需要重复的连接条件
BTW you don't need duplicate join condition in where filter
这篇关于无法隐式转换类型“System.Collections.Generic.IEnumerable<AnonymousType#1>"到'System.Collections.Generic.List<modelClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!