无法将Generic.List <AnonymousType#1>转换为Generic.List <BillEF.Bill>

kyl*_*yle 4 .net linq-to-entities entity-framework c#-4.0

我不确定我是否正确行事.我试着选择一些我从LINQ查询中获取的项目.最终我想要撤回大部分信息,但有些字段是FK ID,因此我必须从其他表中获取其名称值.

我现在遇到的问题是从Anonymous到Bills的列表转换.我该如何解决这个问题?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

我们无法确切地说出来,但我怀疑你能做到:

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();
Run Code Online (Sandbox Code Playgroud)

换句话说,从数据库中提取数据作为匿名类型,但随后返回"手动创建的实体"列表,并复制相关属性.