CRUD操作在多对多关系中首先使用实体​​框架核心2.0代码

时间:2017-12-06 19:04:20

标签: entity-framework asp.net-core entity-framework-core

我在计算机和用户之间有很多关系。不幸的是,关于多对多关系的CRUD操作的例子并不多。最重要的是添加和删除。我试过像computer.ComputerUser.Add(),它的工作原理但删除对我来说很困惑。我甚至都不知道我是否正确地做到了。您的见解会很有帮助。谢谢

// a computer can have one or more Users registered to access
public class Computer
{

    [Key]
    public Guid ComputerId { get; set; }
    public string MachineName { get; set; }
    public DateTime Updated { get; set; }       
    public bool IsActive { get; set; } = true;        
    public virtual ICollection<ComputerUser> ComputerUser { get; set; }

    public Computer()
    {
        this.ComputerUser = new HashSet<ComputerUser>();
    }
}
// an user can have access to one or more computers
public class User
{
   [Key]
   public Guid   GatekeeperUserId { get; set; } 
   public  string Name { get; set; }      
   public virtual ICollection<ComputerUser> ComputerUser { get; set; }

    public GatekeeperUser()
    {
        this.ComputerUser= new HashSet<ComputerUser>();
    }
}

// Joining table 
    [Key]
    public Guid ComputerId { get; set; }
    public  Computer Computer { get; set; }
    [Key]
    public Guid  UserId { get; set; }
    public  User User { get; set; }

2 个答案:

答案 0 :(得分:2)

有什么困惑?它的工作方式与其他任何实体相同:

user.ComputerUser.Remove(computerUser);

我认为你已经挂断了M2M。事实上,这真的不是真正的M2M。您从UserComputerUser有一对多,从ComputerComputerUser有一对多。因此,它就像从任何其他集合中删除任何其他实体一样。

答案 1 :(得分:1)

您可能拥有要从多对多关系中删除的计算机或用户ID。 你可以打电话:

private DeleteComputerUser(User user, Guid computerId)
{
    var computerUser = _dbContext.ComputerUser.SingleOrDefault(computerUser=>
        computerUser.UserId == user.GatekeeperUserId
        && computerUser.ComputerId ==  computerId);
    if (computerUser  != null) 
    {
        _dbContext.ComputerUser.Remove(computerUser);
        _dbContext.SaveChanges();
    }
}

现在用户和具有特定ID的计算机之间的关系消失了。

相关问题