forum

Home / DeveloperSection / Forums / Many-to-many insert with Entity Framework

Many-to-many insert with Entity Framework

Anonymous User 10137 28-Sep-2013

I'm two entities in my Data Model, for example User and Role, both having the ID field as primary key. There's a many-to-many relationship between them. In the database there are three tables: Users, Roles and UsersRoles junction table.

I'm trying to add a new user to the Users table:

using(var myContext = new MyContext)

{
   var user = new User() { ... };
   user.Roles.Add(new Role() { ID = 1 });
}


The same role can be already be used by another Users, so, when I try to add a new User with the same Role, I become Primary key violation as EF tries to add a new record to the Roles table.

Is there any way to tell the Entity Framework not to add a new record to the Roles table, when such role already exists, but only update the Users and UserRoles tables? EF version 1.0

Thanks in advance.


Updated on 28-Sep-2013
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By