5
votes

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?

2

2 Answers

9
votes

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

2
votes

If you're not using databinding, sure. Many to many gets mapped as list of references to each other. User.Roles.Add(Role ...) should be fine.