views:

990

answers:

2

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?

+1  A: 

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.

Arnshea
I don't have an instance of a role, I only have a role id. Will it work if I create a new Role and specify only the id? Is it going to try to insert it in the database? Hopefully not, cuz it already exists there.
adam0101
+2  A: 

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

Alex James
Thanks, I'll try it out and let you know how it goes.
adam0101
Great, it works for me. Thanks
Julien N