Run multiple queries or return multiple value with entity framework
I am basically looking for a way to开发者_开发知识库 run a entity framwork query that will return a subset of result in a tabel as well as the total number of records in a table. I would lik eto do it with one query. I know that I can do a count, then run the querybut that looks like it makes two round trips to the database.
does anyone have any ideas?
You could do it for example with:
var list = context.UserSet.Where(u => u.IsSystemAdmin == 1).Select(u => new {User = u, Count = context.UserSet.Count()}).ToList();
It takes users who have IsSystemAdmin set to 1 and additionaly count of users in whole table.
But this is dumb solution. These are two separate queries and should be queried independently. If there are no users with IsSystemAdmin in table, you won't get count too. It also won't by any faster. Stick to two queries.
Roundtrips aren't bad. It is better in many situations to call two queries, specially with 1-n relations. Using Include
for 1-n relation generates horrible SQL, specially when you do it more than once. It is better to make call without Include
and load 1-n navigation properties separately.
精彩评论