无法隐式转换类型“System.Collections.Generic.IEnumerable<AnonymousType#1>"到'System.Collections.Generic.List<modelClass>
- 作者: 亖呉?盀
- 来源: 51数据库
- 2022-12-13
问题描述
我正在尝试填充 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
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
