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.Roles
collection is declared asvirtual
the 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
Roles
collection to add a new role to the user.But this doesn't mean that you have to remove the
virtual
keyword 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:
Slaumas answer is really good but I would like to add how you can insert a many to many relationship without loading objects from database first. If you know the Ids to connect that extra database call is redundant. The key is to use
Attach()
.More info about Attach:
https://stackoverflow.com/a/3920217/3850405
I am using db-first approach and automapper to map between model and entity (MVC 5) and also using eager loading.
In my scenario, there are equipments and there can be multiple users as equipment operators: