简体   繁体   English

Linq To Sql在多对多关系中查找项目

[英]Linq To Sql Finding item in many to many relationship

Following on from my user scenario here: entity-framework-updating-with-stub-causes-primary-key-violation 接下来是我的用户场景: 实体框架更新存根导致主键冲突

Using EF6, my table structure is as follows: 使用EF6,我的表结构如下:

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. 确实确实可以,但是我认为这效率不高,因为它正在执行2个数据库调用。
How could I rewrite this to be more efficient, ie. 我怎么能重写它以提高效率,即。 one database call? 一个数据库调用?

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. 应该将其转换为单个数据库调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM