问题
I'm working on a basic application in C# Web.
I would like to have 2 objects: - User - Group
Here's the class:
public class User {
public int Id; { get; set; }
public String Username { get; set; }
public String Password { get; set; }
public virtual List<Group> Groups { get; set; }
}
public class Group{
public int Id { get; set; }
public String Name{ get; set; }
public virtual List<User> Users { get; set; }
}
My problem is that when i use this code there's no relation many to many created. I've got a column name "Group_Id" in my table User and a column name "User_Id" in my table Group.
When I use my DbContext class to retrieve Data like this: List groups = db.Groups.ToList(); The attribute "Users" of all my object in "groups" or set to null. So not load by the database.
Can someone explain me how to make this relation many to many work fine ?
回答1:
If you are using Entity Framework, use the ObjectQuery<T>.Include
method:
List groups = db.Groups.Include("Users").ToList()
A reference to the method on MSDN is here.
来源:https://stackoverflow.com/questions/13903638/c-sharp-mapping-many-to-many