Get Total Count and Page Rows in same database trip when using Entity Framework

后端 未结 2 1294
星月不相逢
星月不相逢 2020-12-20 04:40

I am currently using the following method to get a page of customers as well as the total count. The only problem is that I am making 2 database trips - one for getting the

相关标签:
2条回答
  • 2020-12-20 04:53

    I thought and research a lot on this issue. Right now and with EF 6, there are 2 good practices:

    (1) The first solution is to have a Stored Procedure (I know, I Know, you usually want to avoid Stored Procedures when you work with EF, go to solution 2 then!), which returns multiple results. This article explained it:

    Entity Framework Sprocs with Multiple Result Sets

    (2) The second best practice is to use "Query Future" feature of Entity Framework Plus package. This is a very cool extension to Entity Framework and can run multiple queries in one database trip.

    0 讨论(0)
  • 2020-12-20 05:03

    Depending on the cost of the database roundtrip and number of items coming back, it might be faster/easier to perform the base query once and do the paging/count operations on the c# server. i.e.

    var results = (from c in e.Customers
                   where m.Name.Contains(name)
                   select new { c.CustomerId, c.NAME, c.CITY, c.STATE, c.COUNTRY })
                  .Distinct()
                  .OrderBy(s => s.NAME)
                  .ThenBy(s => s.CITY)
                  .ThenBy(s => s.CustomerId)
                  .ToList();
    totalCount = results.Count;
    return results.Skip(skipCount).Take(pageSize).ToList();
    

    This will only perform one database call, but won't perform the paging operations on the sql server.

    Edit:
    Also take a look at this Better way to query a page of data and get total count in entity framework 4.1?

    0 讨论(0)
提交回复
热议问题