Many-to-many insertion and deletion
I have entities
- User:
ID
name
navigation: group
- Group:
ID
name
navigation: user
attitude:
- usrgrp
iduser
idgroup
Here, I don't want to add data to the relationship, not to the main entities. Please give an example of how to remove and insert into usrgrp.
Thanks in advance. from.
Entity Framework is going to include the usrgrp table in the navigation. There will be no object for this. Thus, this table is only accessed through user and group objects. Since this is a many-many relationship, you can access the relationship from either end in the same way.
someUser.Group.Add(new Group());
someUser.Group.Remove(someExistingGroup);
context.SaveChanges();
a source to share
Craig is correct because the table usrgrp
only has 2 FKs, it is a pure join table and therefore the Entity Framework interprets this as a ManyToMany association.
As the code examples that Craig illustrates above show, this is usually fine for most clients.
If you want to manage UserGroup relationships independently, one is to add an extra column to the usrgrp table, which is probably the most convenient identity column. Then the Entity Framework can no longer collapse that table with navigation only, so you will see an Entity object for the usrgrp table that you can manipulate independently.
i.e.
someUser.UserGroups.Add(new UserGroup {User = someUser, Group = someGroup});
Note that you don't need to specify the Identity column (which would be sick) because it was generated by the generated store.
Generally, most customers prefer not to see Entity for pure join tables because the programming experience is easier without it. For example, LINQ queries get a little more complex:
var users = from g in ctx.Groups
from u in g.Users
where g.Name == "Administrators"
select u;
becomes:
var users = from g in ctx.Groups
from ug in g.UserGroups
where g.Name == "Administrators"
select ug.User;
Hope this additional clarification helps
Alex
a source to share