EntityFramework中的多对多SQL查询

时间:2010-12-18 06:24:50

标签: c# sql entity-framework

我需要一些关于sql查询的帮助,我正在使用EntityFramework作为ORM。

我有一个User-- Group Many to Many关系,即一个用户可以属于多个组,一个组可以拥有多个用户。

我完成映射的方式是......

USER tbl,Usr_Grp表和组表,其中PK =主键,FK =外键

USER表有 - > UserId(PK),UserName
组表有 - > GroupId(PK),GroupName
Usr_Grp表有 - > Id(PK),UUserId(FK to usertable),GGroupId(FK to GroupTable)

我面临的问题是......在我的api中,我将得到一组GroupId,我想找到只属于所有这些GroupId的用户(即所有传入的组) )。

有没有办法在实体框架或Sql中编写此查询。我真的很感激我能得到的任何帮助。

-RN

3 个答案:

答案 0 :(得分:6)

联结表Usr_Grp不应该有Id。如果您创建复杂的主键(UUserId,GGroupId),那么EF会自动理解它是多对多关系。

如果您建立如下关系:alt text

然后EF将生成具有多对多关系的实体:alt text

完成所有设置后,您可以轻松使用此类代码:

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();

如果你不能改变模型,那么只需使用这样的linq查询:

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

答案 1 :(得分:0)

试试这个方法:

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

希望它有所帮助!

答案 2 :(得分:0)

    //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:)