Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/Remove many to many associations in Entity Framework

I have three tables in my sample database:

Users

  • ID
  • Username
  • Password

Roles

  • ID
  • Name
  • Description

UserRoles

  • UserID
  • RoleID

UserRoles is a lookup table to simulate a many to many relationship. Adding records to this table allows one to associate records in Users and Roles. My problem is that in Entity Framework it correctly interprets this as a many to many relationship and abstracts away that lookup table.

This works great most of the time, but I'm not sure what to do when I want to add/delete entries from that lookup table. I can delete roles or users but that actually deletes the objects not just their association with each other.

I do know of one option to add a dummy column to the UserRoles lookup table. That will force Entity Framework to turn the lookup table into a full-blown entity, allowing me to add and remove them as lone objects. But I have no need for a dummy column and this seems like a hack. I am looking for better suggestions.

like image 673
Chev Avatar asked Jul 19 '11 15:07

Chev


1 Answers

It should look something like this:

To Remove Relationship

user.Roles.Remove(existingRoleEntity);

To Add Relationship

user.Roles.Add(existingRoleEntity);
like image 142
StriplingWarrior Avatar answered Sep 28 '22 19:09

StriplingWarrior