1

I am using ASP.NET Core with Entity Framework Core. I want to offer a search function for users where they can set the number of desired results, for instance:

SearchModel
{
    public string Name{ get; set; }
    public string Phone { get; set; }
    public int Count { get; set; }
}

Where Count is the desired number of results.

In the response back to the user, I would like to offer the following (besides the actual result/rows of course):

  • The number of results
  • The number of total results for the search filter (in other words how many rows they would have gotten if they did not provide a specific count)
  • The total number of rows (regardless of filter)

This is what I have right now:

var totalCount = await MyDBContext.FirstEntity.CountAsync();

var filterResult = await (from c in MyDBContext.FirstEntity

                        join mt in MyDBContext.SecondEntity
                        on c.SomeID equals mt.SomeID

                        join l in MyDBContext.ThirdEntity
                        on mt.OtherID equals l.OtherID

                        where c.Name.Contains(model.Name)
                        && c.Phone.Contains(model.Phone)

                        select new SomeModel
                        {
                            SomeID = c.SomeID,
                            OtherValue = c.OtherValue,
                            OtherValue = l.OtherValue
                        }

                    )
                    .Distinct()
                    .Take(model.Count)
                    .ToListAsync();

What would be the best way to modify this query so I can the Count() on all rows in filterResult AND the same query without the Take() part?

Is there a way of doing this in a single query, or do I have to perform multiple queries to reach my goal?

Glenn Utter
  • 2,313
  • 7
  • 32
  • 44
  • Possible duplicate of [Better way to query a page of data and get total count in entity framework 4.1?](http://stackoverflow.com/questions/7767409/better-way-to-query-a-page-of-data-and-get-total-count-in-entity-framework-4-1) – esiprogrammer Jan 20 '17 at 13:12
  • I think you are talking about grouping . please try to use GroupBy clause there you can get count as well – Yashveer Singh Jan 20 '17 at 13:12

0 Answers0