如何在Entity Framework Code First中表示Bridge表
我试图找出如何表示两个实体之间的桥接表(多对多关系)我正在使用entity framework代码优先
Student: StudentID int PK StudentName VARCHAR(50) Class: ClassID int PK ClassName VARCHAR(50) StudentClass: StudentID INT PK ClassID INT PK
应该使用什么样的最佳类结构来在entity framework代码中表示它,如何从桥接表中进行选择并插入其中。
我应该像这样代表它们的类:
public class Student { public int StudentId { get; set; } public string StudentName { get; set; } public List Class { get; set; } } public class Class { public int ClassId { get; set; } public string ClassName { get; set; } public List Students { get; set; } }
简而言之: Student
和Class
之间的这种关系类型在EF术语中被称为多对多关系 。
entity framework以一种很好的方式处理参与多对多关系的表。 如果联结表(有时称为桥表,关联表,链接表等)只包含外键而没有其他列,则该表由EF抽象,并且双方获得一个导航属性,暴露另一个的集合侧。
您需要的是首先为上面的表生成实体模型,或者像下面的post中那样定义代码的第一个结构 – 使用Code First创建多对多映射 。
基本上,根据您的结构,您需要将方法OnModelCreating
设置为适合您类中的关系。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
根据您的查询需求,您可以查看以下参考资料:
在Code First中有许多方法可以表示多对多关系。 它实际上取决于您对映射的需求。 如果你只是需要注册地图到目前为止你所拥有的一切。 您正在显示的关系将被Code First识别,并且将自动为您创建一个名为“StudentClasses”的映射表
要在映射表中创建映射,只需执行以下操作:
using(var context = new StudentClassContext()) { Student aStudent = new Student{ StudentName="Johnny", Class = new Class(){ ClassName="Gym"}} context.Students.Add(aStudent); context.SaveChanges(); }
您也可以反向执行此操作:
using(var context = new StudentClassContext()) { Class aClass = new Class{ ClassName = "Gym", Students = new Student(){ StudentName="Johnny"}} context.Classes.Add(aClass); context.SaveChanges(); }
如果您想更加具体和明确地了解关系,可以在重写的上下文OnModelCreating()方法中设置显式映射。 这看起来像这样:
public class StudentClassContext { public DbSet Students { get; set; } public DbSet Classes { get; set; } public StudentClassContext() { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .HasMany(aStudent => aStudent.Classes) // A student can have many classes .WithMany(aClass => aClass.Students)); // Many classes can have many students //.Map(c => c.ToTable("StudentClass); // Set the mapping table to this name } }
如果由于某种原因你需要在代码中或在EntityFramework上下文操作之外访问映射表,我会说创建一个专用的map类并使其成为代码中的一等公民:
上述就是C#学习教程:如何在Entity Framework Code First中表示Bridge表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public class Student { //... } public class Class { //... } // New Map Class public class StudentClassMapRecord { public int Id; // Map record PK public Student Student { get; set; } public Class Class { get; set; } public StudentClassMapRecord(Student aStudent, Class aClass) { Student = aStudent; Class = aClass; } //Uncomment below if you don't need property navigation //public int StudentId { get; set; } //public int ClassId { get; set; } //public StudentClassMapRecord(int studentId, int classId) //{ // StudentId = studentId; // ClassId = classId; //} }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/997799.html