C#多对多映射 [英] C# Mapping Many To Many

查看:70
本文介绍了C#多对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#Web开发基本应用程序.

I'm working on a basic application in C# Web.

我想要2个对象:-用户-小组

I would like to have 2 objects: - User - Group

这是课程:

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; }
}

我的问题是,当我使用此代码时,创建的对象之间并没有多对多的关系.在表用户中有一个列名"Group_Id",在表组中有一个列名"User_Id".

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.

当我使用DbContext类检索数据时,如下所示:列表组= db.Groups.ToList();我所有对象在组"中的属性用户"或设置为null.因此不要由数据库加载.

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 ?

推荐答案

如果使用的是Entity Framework,请使用 ObjectQuery< T> .Include 方法:

If you are using Entity Framework, use the ObjectQuery<T>.Include method:

List groups = db.Groups.Include("Users").ToList()

在MSDN上对该方法的引用是此处.

A reference to the method on MSDN is here.

这篇关于C#多对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆