I have many to many relationship between computer and User. Unfortunately, there are not many examples of CRUD operations on many-to-many relationships. Most importantly adding and deleting. I tried like computer.ComputerUser.Add(), it works but deleting is confusing for me. I don't even know if I am doing it correctly. Your insights will be helpful. Thank you
// 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; }
You probably have Id of Computer or User which you want to remove from many-to-many relation. You can call:
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();
}
}
Now relation between user and computer with specific id is gone.
What's the confusion? It works like any other entity:
user.ComputerUser.Remove(computerUser);
I think you're getting hung up on the M2M. In fact, this is really not a true M2M. You've got a one to many from User
to ComputerUser
and a one to many from Computer
to ComputerUser
. As a result, it works like removing any other entity from any other collection.