I solved this problem earlier by simply adding an Auto-Increment Private Key Identifier column to the lookup table, since the Entity Framework will always hide lookup tables that contain only 2 columns with foreign keys in the end tables. Sometimes you need to add a record directly directly through the Entity Framework , and this will help you with this.
Update from the author of the question
I just wanted to provide an update of my own implementation of this answer. I added an identifier column to the lookup table and created a unique key on two columns of the foreign key to prevent duplicate relationship entries in the table. Now my model is as follows:
http://www.codetunnel.com/content/images/ManyToManyDynamic.jpg
The only thing that sucks is to get a collection of all the related roles that I would have to do:
List<Role> roles = new List<Role>(); foreach (UserRole userRole in myUser.UserRoles) roles.Add(userRole.Role);
This is a bit more, but if there is no equivalent to user.Roles.Remove(role) (something like user.Roles.Associate(existingRoleEntity) ), then this is my only option.
Update:
List<Role> roles = new List<Role>(); foreach (UserRole userRole in myUser.UserRoles) roles.Add(userRole.Role);
Can be achieved with:
IEnumerable<int> roleIDs = myUser.UserRoles.Select(r => r.RoleID); IEnumerable<Role> roles = Entityies.Roles.Where(r => roleIDs.Contains(r.roleID);
You can always use a public partial class to extend User to have the property of returning all roles using the above. Click the link for details on the public partial class things I gave on another question.
source share