Search code examples
many-to-manyef-code-firstdata-annotationsfluent-interface

Composite primary key in many-to-many relationship and column in code first


I guess this is covered somewhere but I'm not able to find. Guess I'm not using the correct search terms.

Basically I have a Many-to-Many table that I define as POCO. You could then also look at it as a table with two one-to-many relations if you wish.

On one end there is a user table and a division table on the other end. However each user-division combo can have several relations, one for each year. So in the associate table there will be a int column for year and the Primary key will be composite from UserId fk, DivisionId fk and Year.

I wasn't sure how to do this in EF 4.1 Code First. I'm hoping there is a DataAnnotation way and a FluentApi way.

If you could point me towards a tutorial that covers this I would really be happy.

User:

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    //some other properties

    public virtual ICollection<DivisionService> Services { get; set; }
}

Division:

public class Division
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DivisionId { get; set; }

    //some other properties

    public virtual ICollection<DivisionService> Services { get; set; }
}

Join/Main table:

public class DivisionService
{
    public int Year { get; set; }  //this and the two foreign keys should be composite Primary Key

    //some other properties

    public virtual User User { get; set; }
    public virtual Division Division { get; set; }
}

Solution

  • You can use HasKey method in FluentAPI and call .HasKey(x => new { x.Year, x.UserId, x.DivisionId }). With data annotations simply specify the [Key] attribute on these three properties.