简体   繁体   English

实体框架通过ID删除N:M关系

[英]Entity Framework remove N:M relation by ids

I have a Simple table like this: 我有一个像这样的简单表:

User(Id, FirstName, ...) <===> Role(Id, Title, ...) 用户(Id,FirstName,...)<===>角色(Id,标题,...)

witch have N:M relation 女巫有N:M的关系

what i want to do is to remove the relation in between them by having there Ids, so my method should be like this : 我想要做的是通过拥有ID来删除它们之间的关系,所以我的方法应该是这样的:

public void UnlinkUsersFromRoles(int[] roleIds, int[] userIds)
{
    var myContext = new DefaultContext();
    // ?? <= how to break the relation without loading unnecessary columns
}

Can you just do this: 你能做到这一点:

var rolesToRemove = myContext.Roles.Where(r=> roleIds.Contains(r.Id)).ToArray();
foreach(var user in myContext.Users.Where(u=> userIds.Contains(u.Id)){
   forearch(var var role in rolesToRemove) {
       user.Roles.Remove(role);
   } 
}
myContext.SaveChanges();

When you say: 当你说:

how to break the relation without loading unnecessary columns 如何在不加载不必要的列的情况下打破关系

You mean, the above code doesn't fullfill you requeriment? 你的意思是,上面的代码并没有满足你的要求吗?

EDIT: 编辑:

If you have a explicity relationship class like UserInRoles, you should use John Castleman Answer, or just create one, map the ForeignKeys and use his solution. 如果您有像UserInRoles这样的明确关系类,您应该使用John Castleman Answer,或者只创建一个,映射ForeignKeys并使用他的解决方案。

If this is many-to-many relationship, there must be a join table in between: for these tables User and Role , let's say it's called UserRole , and is a simple join table (ie, no other columns on that table, other than the FK ids to the other two tables): 如果这是多对多关系,则必须在它们之间有一个连接表:对于这些表UserRole ,假设它叫做UserRole ,并且是一个简单的连接表(即,该表上没有其他列,除了FK ids到另外两个表):

public class UserRole
{
    public int UserId { get; set; }
    public int RoleId { get; set; }
}

With an explicitly defined join table such as this, UnlinkUsersFromRoles could be defined as follows: 使用明确定义的连接表, UnlinkUsersFromRoles可以定义如下:

public void UnlinkUsersFromRoles(int[] roleIds, int[] userIds)
{
    using (var context = new DefaultContext())
    {
        foreach (var ur in context.UserRoles
                                  .Where(u => userIds.Contains(u.UserId))
                                  .Where(r => roleIds.Contains(r.RoleId))
                                  .ToArray())
        {
            context.UserRoles.Remove(ur);
        }

        context.SaveChanges();
    }
}

You're certainly going to wind up loading all the UserRole rows to be removed in when you call ToArray , but this is certainly better than loading in all the related User and Role rows. 当你调用ToArray时,你肯定会最终加载要删除的所有UserRole行,但这肯定比加载所有相关的UserRole行更好。

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

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