我在User
和Group
之间存在多对多关系。
我的API中的操作允许客户端更新Groups
所属的User
。方法是这样的:
public void UpdateUserMembership(int userId, IList<int> groupIds)
{
var user = dbContext.Users
.Include(u => u.Groups)
.First(u => u.Id == userId);
var currentGroups = user.Groups;
// TODO: Sync between the list of ids in groups and currentGroups
dbContext.SaveChanges();
}
因此,方法采用群组的ID ,应相应地更新 user.Groups
(添加或删除群组,以适应给定的ID)< / p>
我怎样才能以正确的方式做到这一点?这是一个我不知道如何处理的常见问题:(
注意:user.Groups
属于UserGroup
类型,是User
和Group
(多对多)之间的“中间”实体。就像这样:
class UserGroup
{
public int GroupId { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public Group Group { get; set; }
}
注意2:我正在使用Entity Framework Core 2
答案 0 :(得分:1)
首先,您可以确定要插入和删除的用户组实体。然后,您可以为这些实体执行数据库操作;
public void UpdateUserMembership(int userId, IList<int> groupIds)
{
var user = dbContext.Users
.Include(u => u.Groups)
.First(u => u.Id == userId);
var currentGroups = user.Groups;
var groupsWhichWillDeleted = currentGroups.Where(x => !groupIds.Contains(x.GroupId)).ToList();
var groupsWhichWillInserted = groupIds.Where(x => !currentGroups.Any(c => c.GroupId == x)).ToList();
foreach (var deletedGroup in groupsWhichWillDeleted)
{
dbContext.UserGroups.Remove(deletedGroup);
}
foreach (var insertedGroupId in groupsWhichWillInserted)
{
var userGroup = new UserGroup { UserId = userId, GroupId = insertedGroupId };
dbContext.UserGroups.Add(userGroup);
}
dbContext.SaveChanges();
}
答案 1 :(得分:0)
您可以获取两个列表之间的差异并将其保存到表中。我还没有经过测试,可能会有不准确的代码。
public void UpdateUserMembership(int userId, IList<int> groupIds)
{
var user = dbContext.Users
.Include(u => u.Groups)
.First(u => u.Id == userId);
var diffIdList = groupIds.Except(user.Groups.SelectMany(x => x.GroupId)).ToList();
foreach (var groupId in diffIdList)
{
var userGroup = new UserGroup { UserId = userId, GroupId = groupId };
dbContext.UserGroups.Add(userGroup);
}
dbContext.SaveChanges();
}