2011-09-15 34 views
2

我確定這個問題之前已經被問過了,但我找不到一個好的方法來搜索它。ef cf linq填充被忽略的屬性

我有如下所示

public class Vendor 
{ 
    public int VendorId { get; set; } 
    public string Name { get; set; } 
    public int ProductCount { get; set; } 
} 

我有一個配置類似設置

public class VendorConfiguration : EntityTypeConfiguration<Vendor> 
{ 
    public VendorConfiguration() 
    { 
     Property(p => p.Name).IsRequired().HasMaxLength(128); 
     Ignore(v => v.ProductCount); 
    } 
} 

這裏一類是我使用抓住廠商查詢。

public Vendor[] GetVendors() 
    { 
     using (var db = new UbidContext()) 
     { 
      var query = (from vendor in db.Vendors 
             select vendor); 

      return query.ToArray(); 
     } 
    } 

我怎麼能填充ProductCount使用子查詢,將類似於

ProductCount = (from vend in db.VendorProducts 
where vend.VendorId == id 
select vend).Count() 

有沒有一種方法,我可以添加到主查詢,所以我只能做1調用D b?

感謝, 安德魯

回答

6

我會嘗試這種方式:

public Vendor[] GetVendors() 
{ 
    using (var db = new UbidContext()) 
    { 
     var query = from vendor in db.Vendors 
        join vp in db.VendorProducts 
         on vendor.VendorId equals vp.VendorId 
        into vendorProducts 
        select new 
        { 
         Vendor = vendor, 
         ProductCount = vendorProducts.Count() 
        }; 

     foreach (var item in query) 
      item.Vendor.ProductCount = item.ProductCount; 

     return query.Select(a => a.Vendor).ToArray(); 
    } 
} 

問題是,你必須投射到非實體類型(在上面的例子中匿名的),然後複製投影ProductCount價值成投影Vendor逐項退貨之前。

+0

非常感謝:),這正是我所期待的。 – no1ross