SelectMany makes too many queries

纵然是瞬间 提交于 2020-01-03 22:05:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!