6

鉴于此 sql 架构:

create table [dbo].[Courses_Students] (
    [DummyColumn] [int] null,
    [CourseId] [int] not null,
    [StudentId] [int] not null,
    primary key ([CourseId], [StudentId])
);

如何在 ? 中定义复合主键和附加列EntityConfiguration

4

1 回答 1

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");
}
于 2010-11-08T14:31:29.757 回答