I’ve been using EF4 (not code-first) since a year, so I’m not really an expert with it.
I’ve a doubt in using many-to-many relationship regarding save n update.
I read somewhere on stackoverflow (i can’t find the url anymore) that one solution – to update an existing many-to-many relation – is to not declare “virtual” property; but, if i do this way, the engine can’t load dataas with easy loading.
Can you pls explain me the reason? Otherwire, could you please help me in finding some cool docs on this theme?
thx
You can update a many-to-many relationship this way (as an example which gives user 3 the role 5):
If the
User.Rolescollection is declared asvirtualthe lineuser.Roles.Add(role);will indeed trigger lazy loading which means that all roles for the user are loaded first from the database before you add the new role.This is in fact disturbing because you don’t need to load the whole
Rolescollection to add a new role to the user.But this doesn’t mean that you have to remove the
virtualkeyword and abandon lazy loading altogether. You can just turn off lazy loading in this specific situation:Edit
If you want to update the whole roles collection of a user I would prefer to load the original roles with eager loading ( =
Include). You need this list anyway to possibly remove some roles, so you don’t need to wait until lazy loading fetches them from the database:Instead of loading the new roles from the database you can also attach them since you know in the example the key property value. You can also remove exactly the missing roles instead of clearing the whole collection and instead of re-adding the exisiting roles: