无法在LINQ to Entities查询中构造实体或复杂类型

Mik*_*lls 7 c# linq entity-framework-4.1

在我们的在线结算应用程序中,我们提供了客户收到的账单及其付款的账单摘要.

为了实现这一点,我必须先付款然后将它们与账单相匹配.所以我做了类似的事情:

foreach (BillPaymentSummary payment in billPayments)
{
    DateTime dt = payment.DueDate;

    // Debug errors on this next line
    var summary = (from a in db.BillHistories
                   where a.CustomerId == customerNumber && a.DueDate == dt && a.Type == "BILL"
                   select new BillSummary
                   {
                       Id = a.Id,
                       CustomerId = a.CustomerId,
                       DueDate = a.DueDate,
                       PreviousBalance = a.PreviousBalance.Value,
                       TotalBill = a.TotalBill.Value,
                       Type = a.Type,
                       IsFinalBill = a.IsFinalBill
                   }).SingleOrDefault();

    if (summary != null)
    {
        summary.PayDate = payment.PaidDate;
        summary.AmountPaid = payment.AmountPaid;
        returnSummaries.Add(summary);
    }
    else
    {
        summary = (from a in db.BillHistories
                   where a.CustomerId == customerNumber && a.DueDate == payment.DueDate && a.Type == "ADJ "
                   select new BillSummary
                   {
                       Id = a.Id,
                       CustomerId = a.CustomerId,
                       DueDate = a.DueDate,
                       PreviousBalance = a.PreviousBalance.Value,
                       TotalBill = a.TotalBill.Value,
                       Type = a.Type,
                       IsFinalBill = a.IsFinalBill
                   }).SingleOrDefault();

        if (summary != null)
        {
            summary.PayDate = payment.PaidDate;
            summary.AmountPaid = payment.AmountPaid;
            returnSummaries.Add(summary);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我一直在玩这个,但不管我做什么,我收到以下错误信息:

无法在LINQ to Entities查询中构造实体或复杂类型"UtilityBill.Domain.Concrete.BillSummary".

是因为我在查询中运行查询吗?我怎样才能解决这个错误?

我曾尝试在谷歌搜索答案并看到很多答案,但似乎没有一个解释我的问题.

Cra*_*aig 6

您无法投影到映射的实体.ToList()在进行映射之前,您必须调用它.

或者更好的是,更改为以下内容(调用FirstOrDefault将执行查询并允许您填充对象):

var summary = db.BillHistories.FirstOrDefault(a => a.CustomerId == customerNumber && a.DueDate == dt && a.Type == "BILL").Select(x => new BillSummary
                               {
                                   Id = a.Id,
                                   CustomerId = a.CustomerId,
                                   DueDate = a.DueDate,
                                   PreviousBalance = a.PreviousBalance.Value,
                                   TotalBill = a.TotalBill.Value,
                                   Type = a.Type,
                                   IsFinalBill = a.IsFinalBill
                               });
Run Code Online (Sandbox Code Playgroud)

要将自己与实体框架分离,您可能还需要考虑使用不同的模型类而不是实体框架模型.