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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With