【发布时间】:2013-07-24 02:14:43
【问题描述】:
在以下返回列表的代码中:
public List<Customer> GeAllCust()
{
var results = db.Customers
.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo })
.ToList()
return results;
}
我收到 C# 无法转换列表的错误报告:
错误:无法将类型
System.Collections.Generic.List<AnonymousType#1>隐式转换为System.Collections.Generic.List<WebApplication2.Customer>
这是为什么呢?
这是一个屏幕截图,显示了 Visual Studio 在错误提示中提供的一些附加信息:
返回一些列而不是整个表是正确的方法吗....?
public object GeAllCust()
{
var results = db.Customers.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo }).ToList();
return results;
}
【问题讨论】:
-
将您的代码和异常粘贴为文本,而不是图像。
-
您需要显式创建
Customer实例。db.Customers已经是IEnumerable<Customer>了吗?如果是这样,您为什么要重新选择这 4 个属性?只需返回db.Customers.ToList()。 (警告:您是否试图从您的数据库中无限制地检索 ALL 个客户?希望您没有太多的填充!)跨度> -
先生....实际上我只想从表中返回 4 个 coloms 而不是整个表...
-
@Hamid,你为什么只需要返回 4 列?
-
先生,像 SQL 查询一样,返回这个 colom.. 我想在实体框架中做同样的事情.. 我想如果我返回整个表,执行表中的数据需要额外的时间...
标签: c# asp.net linq entity-framework