Cannot implicitly convert type #39;System.Collections.Generic.IEnumerablelt;AnonymousType#1gt;#39; to #39;System.Collections.Generic.Listlt;modelClassgt;(无法隐式转换类型“System.Collections.Generic.IEnumerableAnonymousType#1到System.Collections.Generic.ListmodelCl
问题描述
我正在尝试填充 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>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法隐式转换类型“System.Collections.Generic.IEnumer


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01