Yustme
Yustme

Reputation: 6255

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; }
}

Upvotes: 0

Views: 720

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109079

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).

Upvotes: 1

NSGaga
NSGaga

Reputation: 14302

what's wrong with that? - that's the way for a many-to-many composite index...

I'll just post the full example how it's usually done / mapped for many to many with all columns (and typical navigation properties that you probably have already):

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

modelBuilder.Entity<PersonOrder>()
    .HasRequired(x => x.Person)
    .WithMany(x => x.PersonOrders)
    .HasForeignKey(x => x.PersonId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<PersonOrder>()
    .HasRequired(x => x.Order)
    .WithMany(x => x.PersonOrders)
    .HasForeignKey(x => x.OrderId)
    .WillCascadeOnDelete(false);

Upvotes: 1

Related Questions