简体   繁体   English

EntityFramework中的多对多SQL查询

[英]Many to Many SQL query in EntityFramework

I need some help on a sql query, for which I am using EntityFramework as ORM. 我在使用EntityFramework作为ORM的sql查询上需要一些帮助。

I have a User-- Group Many to Many relationship, ie one user can belong to more than one group and one group can have more than 1 user. 我有一个“用户-多对多”组关系,即一个用户可以属于多个组,而一个组可以具有多个用户。

The way I have done the mapping is.. 我完成映射的方式是..

USER tbl, Usr_Grp table, and Group Table where PK = Primary Key, FK = Foreign Key USER tbl,Usr_Grp表和组表,其中PK =主键,FK =外键

USER table has --> UserId(PK) , UserName USER表具有-> UserId(PK),UserName
Group table has --> GroupId (PK), GroupName 组表具有-> GroupId(PK),GroupName
Usr_Grp table has --> Id(PK), UUserId(FK to usertable), GGroupId (FK to GroupTable) Usr_Grp表具有-> Id(PK),UUserId(从FK到usertable),GGroupId(从FK到GroupTable)

The issue that I am facing is... In my api , I will get a set of GroupId's and I want to find only those Users that belong to all these GroupId's ( ie all the groups that are passes in). 我面临的问题是...在我的api中,我将获得一组GroupId,而我只想查找属于所有这些GroupId(即传入的所有组)的那些User。

Is there a way to write this query in entity framework or Sql. 有没有一种方法可以在实体框架或Sql中编写此查询。 I would really appreciate any help I can get on this. 我真的很感谢我能为此提供的任何帮助。

-RN -RN

Junction table Usr_Grp shouldn't have Id. 结点表Usr_Grp不应具有ID。 If you create complex primary key over (UUserId, GGroupId), then EF automatically would understand, that it is Many-To-Many relation. 如果在(UUserId,GGroupId)上创建复杂的主键,则EF会自动理解,这是“多对多”关系。

If you make your relations as follows: 如果您的关系如下: 替代文字

Then EF will generate entities with Many-To-Many relations: 然后,EF将生成具有多对多关系的实体: 替代文字

After you have everything set up you can easily use such code: 完成所有设置后,您可以轻松使用以下代码:

var ids = new List<int>{1, 2, 3, 4}; // GroupIds you need
context.Groups
        .Where(x=> ids.Contains(x.Id))
        .SelectMany(x=>x.Users)
        .Distinct()
        .ToArray();

If you cannot change model, then just use such linq query: 如果您不能更改模型,则只需使用以下linq查询:

context.Grp_Usrs
        .Where(x=> ids.Contains(x.GroupId))
        .SelectMany(x=>x.Users)
        .Distinct()
        .ToArray();

Try this method: 试试这个方法:

var gid = new List<int> {1, 2, 3, 4};
var users_id = entity.Usr_Grp.where(x=> gid.Contains(x.uid);

Hope it helps! 希望能帮助到你!

    //Here is a LinqToSql example but it should work with EF too.Taking into consideration your mappings I would have the following approach in handling a many to many relationship:

    //1. First You need to save you records into the tables as many to many relationship
    [Test]
    public void CanSaveGroupUsers()
    {
        var group = Group { CreatedDate = DateTime.UtcNow, Name = "The Rookies" };
        var groupId = _groupRepository.SaveGroup(group);

        var user = new User { CreatedDate = DateTime.Now, Name = "Justin Bieber" };
        var userId = _userRepository.SaveUser(user);

        var userGroup = new UserGroup { GroupId = groupId, UserId = userId };
        _group.SaveUserGroup(userGroup);
    }

    //2. Then you can retrive them this way:
    [Test]
    public void CanGetGroupUsers()
    {
        var groupIds = new List<int>{1,2,3,4};
        var users = _usersRepository.GetAllUsers();
        var specificUsersList = (users.AsQueryable().Where(user => groupIds.Contains(user.UserGroups.FirstOrDefault().GroupId)));
    }

    //3. I attached my repository code just in case
    public IQueryable<User> GetAllUsers()
    {
        _db.ObjectTrackingEnabled = false;
        return _db.Users;
    }
    public int SaveGroup(Group Group)
    {
        var dbGroup = new Group
        {
            Name = Group.Name,
            CreatedDate = Group.CreatedDate
        };
        _db.Groups.InsertOnSubmit(dbGroup);
        _db.SubmitChanges();
        return dbGroup.Id;
    }

    public int SavUser(User user)
    {
        var dbUser = new User
        {
            CreatedDate = user.CreatedDate,
            Name = user.Name
        };
        _db.Users.InsertOnSubmit(dbUser);
        _db.SubmitChanges();
        return dbUser.UserId;
    }

     public void SaveUserGroup(UserGroup userGroup)
    {
        var dbUserGroup = new UserGroup
        {
            GroupId = userGroup.GroupId,
            UserId = userGroup.UserId

        };
        _db.UserGroups.InsertOnSubmit(dbUserGroup);
        _db.SubmitChanges();
    }

    //Hope this helps:)

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

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