C# Mapping Many To Many

送分小仙女□ 提交于 2021-02-11 13:09:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!