如何使我的linq实体查询更快

时间:2016-09-21 12:07:20

标签: c# entity-framework linq

MediaPlanBillingDetailsMediaPlanPrint的最有效方法是什么,并明智地计算金额总和?基本上MediaPlanBillingDetails是基表。

当前查询:

var sumofallbills= MediaPlanBillingDetails.Sum(m => m.MediaPlanRO.MediaPlanROPrints.Sum(qq => qq.MediaPlanPrint.Amount));

示例数据:

 var aS = new List<MediaPlanBillingDetails>();
        aS.Add(new MediaPlanBillingDetails { BillId = 1, RoID = 1 });
        aS.Add(new MediaPlanBillingDetails { BillId = 1, RoID = 2 });
        aS.Add(new MediaPlanBillingDetails { BillId = 2, RoID = 3 });
        aS.Add(new MediaPlanBillingDetails { BillId = 2, RoID = 4 });
        aS.Add(new MediaPlanBillingDetails { BillId = 3, RoID = 5 });


        var bs = new List<MediaPlanRo>();
        bs.Add(new MediaPlanRo { RoId = 1 });
        bs.Add(new MediaPlanRo { RoId = 2 });
        bs.Add(new MediaPlanRo { RoId = 3 });
        bs.Add(new MediaPlanRo { RoId = 4 });
        bs.Add(new MediaPlanRo { RoId = 5 });

        var cs = new List<MediaPlanRoDetails>();
        cs.Add(new MediaPlanRoDetails { PrintEstimateId = 1, RoId = 1 });
        cs.Add(new MediaPlanRoDetails { PrintEstimateId = 2, RoId = 1 });
        cs.Add(new MediaPlanRoDetails { PrintEstimateId = 3, RoId = 2 });
        cs.Add(new MediaPlanRoDetails { PrintEstimateId = 4, RoId = 3 });
        cs.Add(new MediaPlanRoDetails { PrintEstimateId = 5, RoId = 4 });
        cs.Add(new MediaPlanRoDetails { PrintEstimateId = 6, RoId = 5 });

        var ds = new List<MediaPlanPrint>();
        ds.Add(new MediaPlanPrint { PrintEstimateId = 1, Amount = 1000 });
        ds.Add(new MediaPlanPrint { PrintEstimateId = 2, Amount = 5000 });
        ds.Add(new MediaPlanPrint { PrintEstimateId = 3, Amount = 6000 });
        ds.Add(new MediaPlanPrint { PrintEstimateId = 4, Amount = 8000 });
        ds.Add(new MediaPlanPrint { PrintEstimateId = 5, Amount = 9000 });
        ds.Add(new MediaPlanPrint { PrintEstimateId = 6, Amount = 10000 });

2 个答案:

答案 0 :(得分:1)

如果您没有条件求和,请尝试点击您需要求和的实体,以获取样本:

var result = db.Set<MediaPlanPrint>().Sum(x => x.Amount);

答案 1 :(得分:1)

您尚未发布模型,因此我们只能估计您拥有所有导航属性。您可以尝试以下内容:

var result = db.Set<MediaPlanPrint>()
    .Include(m => m.MediaPlanRoDetails) 
    // Filter according to BillId
    .Where(m => m.MediaPlanRoDetails.MediaPlanRo.MediaPlanBillingDetails.BillId < 100)
    // Group by RoId
    .GroupBy(m => m.MediaPlanRoDetails.RoId)
    .Select(g => new
    {
        RoId = g.Key,
        TotalAmount = g.Sum(m => m.Amount)
    })
    .ToList();