Wednesday, November 25, 2015

Code first Entity Framework composite key which contains a foreign key

I came across the need for a composite key in a code first Entity Framework database for a raffles system. The first table was the raffle setup and would contain an auto generated numeric raffle id and the raffle ticket table would have a relation back to the raffle table (foreign key which was the raffle id).

However as there would be raffles, I needed a non auto generated raffle ticket id which was not unique at a table level, but unique at a raffle level. Being that raffle id 1 could have raffle ticket ids 1 -> 1000 and raffle id 2 could also have raffle tickets 1 -> 1000. Therefore a composite key of raffle ticket id and raffle id (also foreign key was required).

This was achieved by placing a key and foreign key indicator on the raffle id field (on the ticket tabled).
public class Raffle
{
    public int RaffleId { get; set; }
    public virtual List<Ticket> Tickets { get; set; }
}

public class Ticket
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int TicketNumber { get; set; }
    [Key, ForeignKey("Raffle"), Column(Order = 1)]
    public int RaffleId { get; set; }
    public virtual Raffle Raffle { get; set; }
}

No comments:

Post a Comment