Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you insert an entity for a many-to-many relationship? (entity framework)

If I a many-to-many relationship between Users and Roles and I have an instance of a User entity and several Role Ids can I insert a relationship between the two types of entities without having any other Role data and without doing a select on the Roles first?

Update:

I might not have been clear enough. I don't have an instance of a Role, only the role id. Is it possible to create the relationship between User and Role without filling a Role object from the database first?

like image 946
adam0101 Avatar asked Jun 01 '09 20:06

adam0101


People also ask

How do I create a many-to-many relationship in Entity Framework?

To configure many-to-many relationship Using Data Annotations, you need to create the Join Table in the model. The Join Table BookCategory will have properties for the primary key of both the table. It will have two navigational properties one each for Book and Category class.


1 Answers

Yes if you have the IDs and you need to relate them

You should be able to do this (pseudo code)

// how you get this doesn't matter so long as it is in the Context
User user = ...; 
Role role = new Role {Id = 2}; 
// role 2 is in unchanged state
ctx.AttachTo("Roles", role); 
// role 2 is unchanged + added relationship between user and role 2
user.Roles.Add(role); 
ctx.SaveChanges(); 

The key here is that AttachTo puts an entity into the ObjectState manager in the unchanged state. So long as you don't need to modify that entity, and only use if for relationship building, you don't even need to know all the property values, the PK is sufficient.

Once you have it attached you can then build the relationship.

Hope this helps

Cheers Alex

like image 123
Alex James Avatar answered Sep 28 '22 10:09

Alex James