开发者

Junction table with additional columns in EF4 CTP4 Code First

Given this sql schema:

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

How do I define the composite primary key and the additional c开发者_如何学Pythonolumns in the EntityConfiguration?


You need to declare a class 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; }
}

The Key on CourseId, is to prevent a compilation error, you will override it next.

Then, in your DbContext class, you override OnModelCreating like so :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Courses_Students>()
        .HasKey(e => new { e.CourseId, e.StudentId })
        .MapSingleType()
        .ToTable("Courses_Students");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜