views:

126

answers:

2

Hi

I have entities

  • user:

id

name

navigation :group

  • group:

id

name

navigation :user

relation:

  • usrgrp

iduser

idgroup

Here I wan't to add data to relation and not the main entities. Please give me example how to delete and insert into usrgrp.

Thanks in advance. s.

+1  A: 

The Entity Framework is going to subsume the usrgrp table into the navigation. There will not be an entity for it. Therefore, all access to this table is via the User and Group entities only. Since this is a many to many relationship, you can access the relationship from either end in much the same way.

someUser.Group.Add(new Group());
someUser.Group.Remove(someExistingGroup);
context.SaveChanges();
Craig Stuntz
+1  A: 

Craig is right because the usrgrp table has only 2 FKs, it is a pure join table, and as such the Entity Framework interprets this as a ManyToMany association.

As the code samples Craig has above illustrate this is usually fine for most customers.

If however you want to independently manage the UserGroup relationship one option is to add an extra column to the usrgrp table, an Identity Column is probably easiest. The Entity Framework can then no longer collapse this table into just navigations, so you will see an Entity for the usrgrp table that you can manipulate independently.

i.e.

someUser.UserGroups.Add(new UserGroup {User = someUser, Group = someGroup});

Notice you don't have to specify the Identity column (which would be a pain) because it is store generated.

Generally most customers prefer not to see an Entity for pure join tables, because the programming experience is simplier without it. For example LINQ queries become a little more complicated:

this:

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 extra clarification helps

Alex

Alex James
So, how about navigation properties for EF 4.0? :)
Craig Stuntz
Craig I don't get your question. Can you clarify?
Alex James
I want to be able to have properties on subsumed navigations. Right now a table will only be subsumed as many-to-many if if contains only the two keys. I want the ability to have (and read/write), in the client, other fields in the tables used for many-to-many.
Craig Stuntz