Search code examples
ef-code-firstentity-framework-5entity-relationship

Unique index with fluent api


I got a table Person, Order and PersonOrder.

In the table PersonOrder i have a column PersonId and OrderId. How can I create a unique index between these columns with Fluent API?

This was my try:

modelBuilder.Entity<PersonOrder>()
            .HasKey(l => new { l.PersonId , l.OrderId});


[Table("PersonOrder")]
public class PersonOrder
{
    public int PersonId { get; set; }
    public int OrderId{ get; set; }

    public virtual Person Person { get; set; }
    public virtual Order Order { get; set; }
}

Solution

  • I had to think for a while to get what you probably mean. I think you mean that there are non-unique indexes on PersonOrder.PersonId and PersonOrder.OrderId.

    But there is a unique index on the primary key PersonOrder.PersonId + PersonOrder.OrderId. And that's the only thing that should be unique. The index on the individual fields can never be unique. That would mean that the association is in fact not many-to-many, but one-to-many.

    Or is that what you're after: to have a 1 (Person) to many (Orders) association? (With a unique PersonOrder.OrderId). In that case you might as well model the association as a regular 1 to many: Person.Orders and Order.Person (singular).