C# 无法将类型“.List<AnonymousType#1>”隐式转换为“.List<WebApplication2.Customer>”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17836799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot implicitly convert type '.List<AnonymousType#1>' to '.List<WebApplication2.Customer>'
提问by Abdul Khaliq
In the following code that returns a list:
在以下返回列表的代码中:
public List<Customer> GeAllCust()
{
var results = db.Customers
.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo })
.ToList()
return results;
}
I get an error reporting that C# can't convert the list:
我收到一个错误报告,指出 C# 无法转换列表:
Error: Cannot implicitly convert type
System.Collections.Generic.List<AnonymousType#1>
toSystem.Collections.Generic.List<WebApplication2.Customer>
错误:无法将类型隐式转换
System.Collections.Generic.List<AnonymousType#1>
为System.Collections.Generic.List<WebApplication2.Customer>
Why is that?
这是为什么?
Here's a screenshot showing some additional information that Visual Studio provides in a tooltip for the error:
下面的屏幕截图显示了 Visual Studio 在错误工具提示中提供的一些附加信息:
Is it right way to return some columns instead of whole table....?
返回一些列而不是整个表的正确方法......?
public object GeAllCust()
{
var results = db.Customers.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo }).ToList();
return results;
}
采纳答案by gunr2171
When you look the code:
当您查看代码时:
x => new { ... }
This creates a new anonymous type. If you don't need to pull back only a particular set of columns, you can just do the following:
这将创建一个新的匿名类型。如果您不需要只拉回一组特定的列,您可以执行以下操作:
return db.Customers.ToList();
This assumes that Customers
is an IEnumerable<Customer>
, which should match up with what you are trying to return.
这假设它Customers
是一个IEnumerable<Customer>
,它应该与您要返回的内容相匹配。
Edit
编辑
You have noted that you only want to return a certain subset of columns. If you want any sort of compiler help when coding this, you need to make a custom class to hold the values:
您已经注意到您只想返回列的某个子集。如果您在编码时需要任何类型的编译器帮助,您需要创建一个自定义类来保存值:
public class CustomerMinInfo
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public int? ContactNumber { get; set; }
}
Then change your function to the following:
然后将您的功能更改为以下内容:
public List<CustomerMinInfo> GetAllCust()
{
var results = db.Customers.Select(x => new CustomerMinInfo()
{
Name = x.CustName,
Email = x.Email,
Address = x.Address,
ContactNumber = x.CustContactNo
})
.ToList();
return results;
}
This will work, however, you will lose all relationship to the database context. This means if you update the returned values, it will not stick it back into the database.
这将起作用,但是,您将失去与数据库上下文的所有关系。这意味着如果您更新返回的值,它不会将其重新粘贴到数据库中。
Also, just to repeat my comment, returning more columns (with the exception of byte arrays) does not necessarily mean longer execution time. Returning a lot of rows means more execution time. Your function is returning every single customer in the database, which when your system grows, will start to hang your program, even with the reduced amount of columns.
另外,只是重复我的评论,返回更多列(字节数组除外)并不一定意味着更长的执行时间。返回大量行意味着更多的执行时间。您的函数正在返回数据库中的每个客户,当您的系统增长时,即使列数减少,也会开始挂起您的程序。
回答by Mark Avenius
You are selecting to an anonymous type, which is not a Customer
.
您选择的是匿名类型,而不是Customer
.
If you want to do (sort of) this, you can write it like this:
如果你想这样做(有点),你可以这样写:
return db.Customers.Select(x => new Customer { Name = x.CustName, Email = x.CustEmail, Address = x.CustAddress, ContactNo = x.ContactNo }).ToList();
This assumes the properties on your Customer
object are what I called them.
这假设您的Customer
对象上的属性就是我所说的。
** EDIT ** Per your comment,
** 编辑 ** 根据您的评论,
If you want to return a subset of the table, you can do one of two things:
如果要返回表的子集,可以执行以下两种操作之一:
- Return the translated form of
Customer
as I specified above, or: - Create a new class for your business layer that only has only those four fields, and change your method to return a
List<ShrunkenCustomer>
(assumingShunkenCustomer
is the name that you choose for your new class.)
- 返回
Customer
我上面指定的翻译形式,或者: - 为您的业务层创建一个只有这四个字段的新类,并更改您的方法以返回 a
List<ShrunkenCustomer>
(假设ShunkenCustomer
是您为新类选择的名称。)
回答by robasta
GetAllCust()
is supposed to return a List of Customer
, Select
New will create a list of Anonymous Types, you need to return a list of Customer from your query.
try:
GetAllCust()
应该返回一个 List of Customer
,Select
New 将创建一个匿名类型列表,您需要从您的查询中返回一个 Customer 列表。尝试:
var results = db.Customers.Select( new Customer{CustName = x.CustName}).ToList(); //include other fields
回答by kumaheiyama
I guess Customer
is a class you have defined yourself?
The my suggestion would be to do something like the following:
我猜Customer
是你自己定义的一个类吗?我的建议是执行以下操作:
var results = db.Customers.Select(x => new Customer(x.Custname, x.CustEmail, x.CustAddress, x.CustContactNo)).ToList();
The reason is that you are trying to return a list of Customer
but the results from your link is an anonymous class containing those four values.
This would of course require that you have a constructor that takes those four values.
原因是您试图返回一个列表,Customer
但链接的结果是一个包含这四个值的匿名类。这当然需要您有一个接受这四个值的构造函数。
回答by saktiprasad swain
Basically whatever u got in var type, loop on that and store it in list<> object then loop and achieve ur target.Here I m posting code for Master details. List obj = new List();
基本上无论你在 var 类型中得到什么,循环并将其存储在 list<> 对象中,然后循环并实现你的目标。这里我发布了 Master 详细信息的代码。List obj = new List();
var orderlist = (from a in db.Order_Master
join b in db.UserAccounts on a.User_Id equals b.Id into abc
from b in abc.DefaultIfEmpty()
select new
{
Order_Id = a.Order_Id,
User_Name = b.FirstName,
Order_Date = a.Order_Date,
Tot_Qty = a.Tot_Qty,
Tot_Price = a.Tot_Price,
Order_Status = a.Order_Status,
Payment_Mode = a.Payment_Mode,
Address_Id = a.Address_Id
});
List<MasterOrder> ob = new List<MasterOrder>();
foreach (var item in orderlist)
{
MasterOrder clr = new MasterOrder();
clr.Order_Id = item.Order_Id;
clr.User_Name = item.User_Name;
clr.Order_Date = item.Order_Date;
clr.Tot_Qty = item.Tot_Qty;
clr.Tot_Price = item.Tot_Price;
clr.Order_Status = item.Order_Status;
clr.Payment_Mode = item.Payment_Mode;
clr.Address_Id = item.Address_Id;
ob.Add(clr);
}
using(ecom_storeEntities en=new ecom_storeEntities())
{
var Masterlist = en.Order_Master.OrderByDescending(a => a.Order_Id).ToList();
foreach (var i in ob)
{
var Child = en.Order_Child.Where(a => a.Order_Id==i.Order_Id).ToList();
obj.Add(new OrderMasterChild
{
Master = i,
Childs = Child
});
}
}