2013-02-26 98 views
1

使用C#4和EF5。Linq to Entities Group Sum計算的屬性

有麻煩,試圖總結計算特性:

The specified type member 'QtyAvailable' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. 

下面是屬性定義:

public decimal QtyAvailable 
    { 
     get 
     { return this.QtyInContainer - this.QtyAllocated; } 
    } 

這裏是LINQ的:

var viewModel = 
       companyItems 
         .GroupJoin(
          inventory, 
          items => items.Id, 
          inven => inven.ItemId, (im, icd) => new { im, icd } 
          ) 
         .SelectMany(
          itemInven => itemInven.icd.DefaultIfEmpty(), 
          (im, icd) => new { im, icd } 
         ) 
         .GroupBy(g => new 
          { 
           g.im.im.Id 
          } 
         ) 
         .Select(group => 
           new ItemAvailabilityViewModel() 
           { 
            Id = group.Key.Id, 
            QtyAvailable = group.Sum(jt => jt.icd == null ? 0 : jt.icd.QtyAvailable), 
            UnitCashPrice = group.Max(jt => jt.im.im.UnitSellPrice), 
            UnitCreditPrice = group.Max(jt => jt.im.im.UnitSellPrice * (1 + company.CashDiscountPct)), 
            CustomerUnitPrice = group.Max(jt => jt.im.im.UnitSellPrice * (1 + decCreditPriceMarkup)) 
           } 
         ) 
         ; 

不知道如何實現這個結果。我需要以某種方式將其分解爲2個查詢嗎?

回答

2

看起來像把這個分解成2個查詢就是票。從我猜想發生的事情來看,第一次,當你調用.ToList()時,它解析了計算的屬性,使得它本質上不再爲第二個查詢計算然後求和。這裏是結果代碼:

//join of Recpt Header and Detail 
      var unGroupedJoin = 
       companyItems 
         .GroupJoin(
          inventory, 
          items => items.Id, 
          inven => inven.ItemId, (im, icd) => new { im, icd } 
          ) 
         .SelectMany(
          itemInven => itemInven.icd.DefaultIfEmpty(), 
          (im, icd) => new { im, icd } 
         ).ToList(); 

      var viewModel = 
       unGroupedJoin 
         .GroupBy(g => new 
          { 
           g.im.im.Id 
          } 
         ) 
         .Select(group => 
           new ItemAvailabilityViewModel() 
           { 
            Id = group.Key.Id, 
            QtyAvailable = group.Sum(jt => jt.icd == null ? 0 : jt.icd.QtyAvailable), 
            UnitCashPrice = group.Max(jt => jt.im.im.UnitSellPrice), 
            UnitCreditPrice = group.Max(jt => jt.im.im.UnitSellPrice * (1 + company.CashDiscountPct)), 
            CustomerUnitPrice = group.Max(jt => jt.im.im.UnitSellPrice * (1 + decCreditPriceMarkup)) 
           } 
         ).ToList() 
         ;