[英]Cannot convert Generic.List<AnonymousType#1> to Generic.List<BillEF.Bill>
I'm not sure if I'm going about this right. 我不确定我是否正确行事。 I'm try to select just a few items that I get back from the LINQ query.
我试着选择一些我从LINQ查询中获取的项目。 Eventually I'll want to pull back most of the information, but some of the fields are FK ID's so I'll have to get their name values from other tables.
最终我想要撤回大部分信息,但有些字段是FK ID,因此我必须从其他表中获取其名称值。
The problem I'm having right now is the list conversion from Anonymous to Bills. 我现在遇到的问题是从Anonymous到Bills的列表转换。 How do I get around this?
我该如何解决这个问题?
public class BillDO
{
/// <summary>
/// Returns all user bills based on their UserName
/// </summary>
/// <param name="UserName"></param>
/// <returns></returns>
public List<Bill> GetBills(string UserName)
{
BillsEntities be = new BillsEntities();
var q = from b in be.Bills
where b.UserName == UserName
orderby b.DueDate
select new { b.DueDate, b.Name, b.PaymentAmount, b.URL };
List<Bill> billList = q.ToList();
return billList;
}
}
We can't really tell for sure, but I suspect you could do: 我们无法确切地说出来,但我怀疑你能做到:
var q = from b in be.Bills
where b.UserName == UserName
orderby b.DueDate
select new { b.DueDate, b.Name, b.PaymentAmount, b.URL };
return q.AsEnumerable()
.Select(b => new Bill { DueDate = b.DueDate,
Name = b.Name,
PaymentAmount = b.PaymentAmount,
URL = b.URL })
.ToList();
In other words, pull the data from the database as anonymous types, but then return a list of "manually created entities" with the relevant properties copied over. 换句话说,从数据库中提取数据作为匿名类型,但随后返回“手动创建的实体”列表,并复制相关属性。
As @Jon Skeet said, we don't know what a Bill
looks like, but going from context, to make this work you need: 正如@Jon Skeet所说,我们不知道
Bill
样子,但是从背景来看,要做到这一点,你需要:
public List<Bill> GetBills(string UserName)
{
BillsEntities be = new BillsEntities();
return new List<Bill>(from b in be.Bills
where b.UserName == UserName
orderby b.DueDate
select new Bill {
DueDate = b.DueDate,
Name = b.Name,
PaymentAmount = b.PaymentAmount,
Url = b.URL
});
}
This assumes that the properties you selected mirror the exact properties in your Bill
class and that there won't be any null reference exceptions or bad constructor arguments. 这假定您选择的属性镜像了
Bill
类中的确切属性,并且不会有任何空引用异常或错误的构造函数参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.