I have two tables, one called Users and one called Groups. I also have one relationship table called GroupUsers with PK from Groups and Users.
I can add user 1 with group 2 with:
var group = db.Groups.Find(2);
var user = db.Users.Find(1);
group.Users.Add(user);
db.SaveChanges();
But how do I select relations from the GroupUsers table? I want to print out all users that belong to a group using LINQ.
You can easily navigate relationships in Entity Framework using navigation properties.
In this case the
Group.UsersandUser.Groupsare navigation properties since they represent the relationship between theGroupandUserentities.This example will return all users who belong to the group with primary key value of
1:See also: