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 に答える