问题
I have dynamic fields inside usergroups and I want to select them based on what usergroups user is.
Basically I want to simulate query like .Where(x => x.UserGroupId == x || ...
because otherwise it makes about 20 queries just to get dynamicfields.
Maybe I can somehow pass array of integers as UserGroupId
and it will simulate the query with ||
.
Here is my example, both results output is same, only difference is that first one has 20 queries to database and second has only 1.
public IEnumerable<UserGroup> UserGroups
{
get
{
var db = new MainDataContext();
return db.UserGroupUsers.Where(x => x.UserId == this.Id).Select(x => x.UserGroup);
}
}
public IEnumerable<UserDynamicField> DynamicFields
{
get
{
var db = new MainDataContext();
var fields = this.UserGroups.SelectMany(x => x.UserGroupDynamicFields); // 20+ queries
var fields2 = db.UserGroupDynamicFields.Where(x =>
x.UserGroupId == 1 ||
x.UserGroupId == 2 ||
x.UserGroupId == 3 ||
x.UserGroupId == 4 ||
x.UserGroupId == 5 ||
x.UserGroupId == 6 ||
x.UserGroupId == 7 ||
x.UserGroupId == 8 ||
x.UserGroupId == 9 ||
x.UserGroupId == 10); // 1 query, maybe I can somehow pass array of Id's here?
}
}
回答1:
Try converting it to an IQueryable<T>
instead of an IEnumerable<T>
:
public IQueryable<UserGroup> UserGroups
{
get
{
var db = new MainDataContext();
return db.UserGroupUsers.Where(x => x.UserId == this.Id)
.Select(x => x.UserGroup);
}
}
public IQueryable<UserDynamicField> DynamicFields
{
get
{
// 1 query
return this.UserGroups.SelectMany(x => x.UserGroupDynamicFields);
}
}
This will allow Linq to take advantage of the fact that it doesn't have to pull the result set in memory until it's iterated, so this will be translated to a conventional SQL join.
来源:https://stackoverflow.com/questions/17710825/selectmany-makes-too-many-queries