无法将Generic.List <anonymoustype#1>转换为Generic.List <billef.bill> </billef.bill> </anonymoustype#1>

时间:2011-09-14 14:49:46

标签: .net entity-framework c#-4.0 linq-to-entities

我不确定我是否正确行事。我试着选择一些我从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;
    }
}

2 个答案:

答案 0 :(得分: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();

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

答案 1 :(得分:1)

正如@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
            });
}

这假定您选择的属性镜像了Bill类中的确切属性,并且不存在任何空引用异常或错误的构造函数参数。