如何为此做出更好的LINQ查询

时间:2013-04-27 15:44:08

标签: c# asp.net-mvc-3 entity-framework

我正在使用Entity Framework在MVC3中完成我的项目。我对LINQ没有多少经验。但我设法根据我的要求编写代码。现在,问题在于,我的逻辑需要更多时间来处理查询,因为我使用 foreach 拆分我的查询,并且数据库中的单列中有三种不同的类型。我试图使用LINQ本身编写完整的逻辑。但对我没有任何帮助。

我需要一个建议,即如何更改逻辑以提高代码性能。请帮助我。

行动方法代码

        public decimal ReturnAmount(int Id, int Year)
    {

        var UsersWithDeptId = db.Users.Where(asd => asd.UserDeptId == Id).Select(asd => asd.Id).ToList();
        var ListUserValue = (from cap in db.CareAllocationPercents
                             where cap.Type == 1 && UsersWithDeptId.Contains(cap.UserId)
                             select new UserWithDeptId
                             {
                                 Year = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Year).FirstOrDefault(),
                                 Amount = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Amount).FirstOrDefault(),
                                 UserId = cap.UserId,
                                 UserDeptId = (from userdept in db.Users where userdept.Id == cap.UserId select userdept.UserDeptId).FirstOrDefault(),
                                 Percentage = cap.Percentage,
                                 CareItemId = cap.CareItemId,
                                 Category = "User",
                                 CareAllocationId = cap.Id
                             }).ToList();

        ListUserValue = ListUserValue.Where(asd => asd.Year == Year).ToList();

        List<int> RouteIds = db.CareAllocationPercents.Where(asd => asd.Type == 3).Select(asd => asd.UserId).ToList();
        var UsersWithRoutingId = (from route in db.RoutingListMembers
                                  where RouteIds.Contains(route.RoutingListId.Value) && route.User.UserDeptId == Id
                                  select
                                      new RoutingWithUser
                                      {
                                          UserId = route.UserId,
                                          RoutingId = route.RoutingListId
                                      }).ToList();

        var ListRouteValue = (from cap in db.CareAllocationPercents
                              where cap.Type == 3
                              select new UserWithDeptId
                              {
                                  Year = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Year).FirstOrDefault(),
                                  Amount = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Amount).FirstOrDefault(),
                                  UserId = cap.UserId,
                                  UserDeptId = (from userdept in db.Users where userdept.Id == cap.UserId select userdept.UserDeptId).FirstOrDefault(),
                                  Percentage = cap.Percentage,
                                  Category = "Route",
                                  CareItemId = cap.CareItemId,
                                  CareAllocationId = cap.Id
                              }).ToList();

        List<UserWithDeptId> NewRouteList = new List<UserWithDeptId>();
        ListRouteValue = ListRouteValue.Where(asd => asd.Year == Year).ToList();

        foreach (var listdept in ListRouteValue)
        {
            var user = UsersWithRoutingId.Where(uwri => uwri.RoutingId == listdept.UserId).FirstOrDefault();
            if (user != null)
            {
                NewRouteList.Add(new UserWithDeptId { UserId = user.UserId, Year = listdept.Year, UserDeptId = db.Users.Where(asd => asd.Id == user.UserId).Select(asd => asd.UserDeptId).FirstOrDefault(), Percentage = listdept.Percentage, CareItemId = listdept.CareItemId, Amount = listdept.Amount, CareAllocationId = listdept.CareAllocationId, Category = listdept.Category });
            }
        }

        NewRouteList = NewRouteList.Where(asd => asd.UserDeptId == Id).ToList();
        var ListUserId = (from user in db.Users
                          where user.UserDeptId == Id
                          select new UserWithDeptId
                          {
                              UserId = user.Id
                          }).ToList();

        var ListDeptId = (from cap in db.CareAllocationPercents
                          where cap.Type == 2 && cap.UserId == Id
                          select new UserWithDeptId
                          {
                              Year = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Year).FirstOrDefault(),
                              Amount = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Amount).FirstOrDefault(),
                              UserDeptId = cap.UserId,
                              Percentage = cap.Percentage,
                              Category = "Dept",
                              CareItemId = cap.CareItemId,
                              CareAllocationId = cap.Id,
                          }).ToList();

        ListDeptId = ListDeptId.Where(asd => asd.Year == Year).ToList();
        int UserCount = ListUserId.Count;
        List<UserWithDeptId> NewList = new List<UserWithDeptId>();

        foreach (var listdept in ListDeptId)
        {
            foreach (var users in ListUserId)
            {
                NewList.Add(new UserWithDeptId { UserId = users.UserId, UserDeptId = listdept.UserDeptId, Percentage = listdept.Percentage, CareItemId = listdept.CareItemId, Amount = listdept.Amount, CareAllocationId = listdept.CareAllocationId, Category = listdept.Category });
            }
        }
        int CountUser = ListUserValue.Count;
        int RouteCount = NewRouteList.Count;
        NewList.AddRange(ListUserValue);
        NewList.AddRange(NewRouteList);
        List<CAREReviewBefore> NewModelList = new List<CAREReviewBefore>();
        foreach (var mod in NewList)
        {
            CAREReviewBefore cr = new CAREReviewBefore();
           // int? BibId = (from pod in db.PoDetails where pod.Id == (from por in db.CareItems where por.Id == mod.CareItemId select por.PoReceipt.PoDetailId).FirstOrDefault() select pod.BibId).FirstOrDefault();
            int? InvoiceId = (from asd in db.PoReceipts
                              where asd.Id == (from careits in db.CareItems where careits.Id == mod.CareItemId select careits.PoRecId).FirstOrDefault()
                              select asd.InvoiceId).FirstOrDefault();

            //Current Currency Rate

            var Rate = db.Invoices.Where(In => In.Id == InvoiceId).Select(In => In.Rate).FirstOrDefault();
            var CurrencyRate = db.Invoices.Where(inv => inv.Id == InvoiceId).Select(inv => inv.Currency.Rate).FirstOrDefault();
            decimal Rat = 0;
            if (Rate != null || Rate != 0)
            {
                Rat = Convert.ToDecimal(Rate);
                if (Rat == 0)
                {
                    Rat = Convert.ToDecimal(CurrencyRate);
                }
                cr.Tot_Annual_SubCost = mod.Amount * Rat;
            }

            if (mod.Category == "User")
            {
                cr.Allocated_Cost_to_Dept = (((mod.Amount * mod.Percentage) / (100)) * Rat);
            }
            else if (mod.Category == "Dept")
            {
                cr.Allocated_Cost_to_Dept = (((mod.Amount * mod.Percentage) / (UserCount * 100)) * Rat);
            }
            else if (mod.Category == "Route")
            {
                cr.Allocated_Cost_to_Dept = (((mod.Amount * mod.Percentage) / (RouteCount * 100)) * Rat);
            }
            NewModelList.Add(cr);

        }
        var Amount = NewModelList.Sum(asd => asd.Allocated_Cost_to_Dept);
        return Amount;
    }

谢谢,

3 个答案:

答案 0 :(得分:2)

目前唯一能引起我注意的是你正在制作的.ToList()电话。 .ToList()将实现IQueryable,它将对数据库执行查询。我建议尽可能少地这样做,以便可以对数据库运行大部分查询,而不是拉回所有表行,然后在代码中过滤它。

我提出的另一个建议是在Sql Server Profiler中设置跟踪并观察您对数据库实际执行的查询。

答案 1 :(得分:0)

我建议你使用实体框架分析器,我已经使用了他们的nhibernate探测器,它真的很好,遗憾的是它'不是免费的,但试用版给你足够的时间。

http://www.hibernatingrhinos.com/products/EFProf

答案 2 :(得分:0)

一个改进是在获取过滤器所需的数据后一次获取列表:

from cap in db.CareAllocationPercents
where (cap.Type == 1 && UsersWithDeptId.Contains(cap.UserId))
   || (cap.Type == 2 && cap.UserId == Id)
   || cap.Type == 3
select new UserWithDeptId
{
    Year = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Year).FirstOrDefault(),
    Amount = (from amt in db.CareAllocations where amt.CareItemId == cap.CareItemId select amt.Amount).FirstOrDefault(),
    UserId = cap.UserId,
    UserDeptId = (from userdept in db.Users where userdept.Id == cap.UserId select userdept.UserDeptId).FirstOrDefault(),
    Percentage = cap.Percentage,
    CareItemId = cap.CareItemId,
    Category = "User",
    CareAllocationId = cap.Id,
    Type = cap.Type
})

在上一部分中,您使用Type代替mod.Category来计算正确的Allocated_Cost_to_Dept金额。