鉴于此sql架构:
create table [dbo].[Courses_Students] (
[DummyColumn] [int] null,
[CourseId] [int] not null,
[StudentId] [int] not null,
primary key ([CourseId], [StudentId])
);
如何在EntityConfiguration
?
答案 0 :(得分:6)
您需要声明一个班级Courses_Students
public class Courses_Students
{
[Key]
public int CourseId { get; set; }
public int StudentId { get; set; }
public int DummyColumn { get; set; }
public virtual ICollection<Course> Courses { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
CourseId上的Key是为了防止编译错误,接下来会覆盖它。
然后,在您的DbContext类中,您重写OnModelCreating,如下所示:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Courses_Students>()
.HasKey(e => new { e.CourseId, e.StudentId })
.MapSingleType()
.ToTable("Courses_Students");
}