Question

Following on from my user scenario here: entity-framework-updating-with-stub-causes-primary-key-violation

Using EF6, my table structure is as follows:

Users - UserCodePK, UserName
UserGroups - UserCodeFK,GroupCodeFK
Groups - GroupCodePK,GroupDescription

I am attempting to write a method to return whether a user has an occurence of any group in a list:

public static bool InUserGroup(string userCode, List<string> userGroupList)
{
    using (var dbContext = new MyEntities())
    {
        var results = dbContext.Users.Where(u => u.UserCodePK == userCode).FirstOrDefault();
        return results.UserGroups.Where(ug => userGroupList.Contains(ug.GroupCodePK)).Any();                     
    }
}

This does indeed work, but I don't think it is very efficient as it is doing 2 database calls.
How could I rewrite this to be more efficient, ie. one database call?

Was it helpful?

Solution

You could try doing it like that:

return dbContext.Users.Where(u => u.UserCodePK == userCode 
     && u.UserGroups.Where(ug => userGroupList.Contains(ug.GroupCodePK)).Any();

It should get translated into single database call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top