Connection 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 to define a composite primary key and additional columns in EntityConfiguration ?

+6
entity-framework
source share
1 answer

You need to declare Courses_Students class

 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, then you will override it.

Then, in your DbContext class, you override OnModelCreating as follows:

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

All Articles