2013-01-21 85 views
0

我有一個ASP.NET MVC4項目與實體框架。用lambda表達式計算記錄數

如何到計數(帶有lambda表達式)請求的數量相關的MaterialPackingID = 123?

這裏是我的課:

public class Request 
{ 
    [Key] 
    public virtual int RequestID { get; set; } 
    public virtual ICollection<TransportedMaterial> TransportedMaterials { get; set; } 
} 

public class TransportedMaterial 
{ 
    [Key] 
    public int TransportedMaterialID { get; set; }     
    public MaterialPacking MaterialPacking { get; set; } 
} 


public class MaterialPacking 
{ 
    public int MaterialPackingID { get; set; } 
    public string DescriptionFr { get; set; } 
    public string DescriptionNl { get; set; } 
} 

所以:

  • 1請求可能包含幾個TransportedMaterial

  • 1 TransportedMaterial包含1 MaterialPacking

以下是我的嘗試:

public int CountExistingRequestsFilterByMaterialPacking(int id) 
    { 
     using (var unitOfWork = UnitOfWorkFactory.Create()) 
     { 
      var requestRepository = unitOfWork.Create<Request>(); 
      var materialPackingRepository = unitOfWork.Create<MaterialPacking>(); 
      var materialPacking = materialPackingRepository.SingleOrDefault(x => x.MaterialPackingID == id); 

      if (materialPacking == null) 
       throw new FaultException("Packing not found"); 

      return requestRepository.GetAll().Where(x => x..... == materialPacking.MaterialPackingID).Count(); 
     } 
    } 

謝謝。

+0

? –

+0

您可以使用'Count(expression)'方法進行計數。它不能解決你的問題嗎? –

回答

0

做這樣的工作?

return requestRepository.GetAll().Count(req => 
    req.TransportedMaterials.Any(tm => 
     tm.MaterialPacking.MaterialPackingID == materialPacking.MaterialPackingID) 
    ); 

假設:你要包含有MaterialPackingID匹配一個一個或多個TransportedMaterial對象請求的計數你有興趣在沒有你已經嘗試用什麼方式什麼不行

+0

非常感謝。這就是我需要的。 – Bronzato