6

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 columns in the EntityConfiguration?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ismael
  • 361
  • 3
  • 9

1 Answers1

6

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");
}
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • But i was expecting to have actually navigation properties in the Courses_Students class. At least, that's what I get when generating the model with the EF designer. – Ismael Nov 08 '10 at 15:18
  • Thanks Christian, this answer helped me out. :] – Gleno Jun 18 '11 at 02:45