cho*_*bo2 0 c# entity-framework
如果我有学生和课程的经典例子,请说.学生可以有很多课程,课程可以有很多学生.
如果我想在许多表格部分添加额外的字段,如何在EF 6代码中创建中间表?
我只是在代码中创建另一个类,然后以某种方式将其挂起?
DB上下文
public class MyContext : DbContext
{
public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
{
// this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
[Key]
public Guid StudentCourseId { get; set; }
public Guid StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; } // Include this so you can access it later
public Guid CourseId { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
public int Permissions { get; set; }
}
public class Course
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; } = new >();
}
public class Student
{
[Key]
public Guid Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Course> Courses { get; set; } = new List<Course>();
}
Run Code Online (Sandbox Code Playgroud)
鉴于你是代码,我会做类似以下的事情.
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}
public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Students { get; set; }
}
public class StudentCourse
{
[Key]
public int StudentCourseId { get; set; }
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public Student Student { get; set; } // Include this so you can access it later
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
编辑:想要注意与数据属性建立关系,您也可以使用EF Fluent API建立您的关系.属性看起来一样,但没有[ForeignKey("")]
归档时间: |
|
查看次数: |
1029 次 |
最近记录: |