使用lambda表达式计算记录数

时间:2013-01-21 16:50:56

标签: asp.net-mvc entity-framework entity-framework-4

我有一个带有Entity Framework的ASP.NET MVC4项目。

如何计算(带有lambda表达式)相关MaterialPackingID = 123的Request数量?

以下是我的课程:

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();
        }
    }

感谢。

1 个答案:

答案 0 :(得分:0)

这样的事情有用吗?

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

假设:您需要包含一个或多个TransportedMaterial对象的请求计数,这些对象的MaterialPackingID与您感兴趣的对象相匹配。