如何在实体框架代码中表示桥表首先 [英] How to represent Bridge table in Entity Framework Code First

查看:113
本文介绍了如何在实体框架代码中表示桥表首先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出我如何代表两个实体之间的桥梁表(多对多关系)
我正在使用实体框架代码首先

 学生:
StudentID int PK
StudentName VARCHAR(50)

类:
ClassID int PK
ClassName VARCHAR(50)

StudentClass:
StudentID INT PK
ClassID INT PK

我应该使用什么最好的类结构来代表实体框架代码首先,我如何从桥表中选择并插入。



我应该代表这样的类:

  public class Student 
{
public int StudentId {get;组; }
public string StudentName {get;组; }

public List< Class> Class {get;组; }

}


public class Class
{
public int ClassId {get;组; }
public string ClassName {get;组; }

public List< Student>学生{get;组; }
}


解决方案

Student Class 之间的这种关系类型称为多对多关系在EF术语中。


实体框架以很好的方式处理参与多对多关系的表。如果连接表(有时称为桥表,关联表,链接表等)仅由外键组成,而不包含其他列,那么该表将被EF抽象,双方将获得一个导航属性,


您将需要先为上述表生成实体模型,或定义您的代码第一个结构,如下所示后 - 创建多个使用代码优先的映射



基本上,根据您的结构,您需要设置方法 OnModelCreating 适用于你的课程中的关系。

  protected override void OnModelCreating(DbModelBuilder modelBuilder)

根据您的查询需求,您会发现有兴趣了解t他以下参考文献:




I am trying to find out how I can represent a bridge table between two entities (many to many relation) I'm Using Entity Framework Code First

Student:
   StudentID int  PK
   StudentName VARCHAR(50)

Class:
   ClassID int PK
   ClassName VARCHAR(50)

StudentClass:
   StudentID INT PK
   ClassID INT PK

What is the best Class Structure should i Use to represent it in Entity Framework Code First and how can i select from the bridge table and insert in it.

Should I represent the classes it like this:

    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public List<Class> Class { get; set; }

    }


    public class Class
    {
        public int ClassId { get; set; }
        public string ClassName { get; set; }

        public List<Student> Students { get; set; }
    }

解决方案

In short: This relationship type between Student and Class is called many to many relationship in EF terminology.

Entity framework handles tables participating in Many to Many relationship in a nice manner. If the junction table (sometimes called bridge table, association table, link table, etc) only consists of the foreign keys and no other columns, then that table is abstracted by EF and the two sides get a navigational property exposing a collection of the other side.

What you would need is to generate a Entity Model for the above tables first or define your code first structure like in the following post - Creating a Many To Many Mapping Using Code First.

Basically, depending on your structure you need to set the method OnModelCreating appropriate to the relationships in your classes.

protected override void OnModelCreating(DbModelBuilder modelBuilder)

Depending on your query needs you will find it informative to look at the following references:

这篇关于如何在实体框架代码中表示桥表首先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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