ihisham
ihisham

Reputation: 248

Composite unique Index

i have the following models, i want to specify using FluentApi that the paire in table A, B.Id and C.Id are unique

class A
{
    public int Id { get; set; }
    public B B { get; set; }
    public C C { get; set; }
}
class B
{
    public int Id { get; set; }
}
class C
{
    public int Id { get; set; }
}

Upvotes: 1

Views: 248

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205589

It's not possible with just navigation properties.

You need to add the explicit FK fields:

class A
{
    public int Id { get; set; }
    public int B_Id { get; set; }
    public int C_Id { get; set; }
    public B B { get; set; }
    public C C { get; set; }
}

and create an unique index using the following Fluent API configuration:

modelBuilder.Entity<A>().HasRequired(e => e.B).WithMany().HasForeignKey(e => e.B_Id);
modelBuilder.Entity<A>().HasRequired(e => e.C).WithMany().HasForeignKey(e => e.C_Id);

modelBuilder.Entity<A>().Property(e => e.B_Id).HasColumnAnnotation("Index", 
    new IndexAnnotation(new IndexAttribute("IX_BC", 1) { IsUnique = true }));
modelBuilder.Entity<A>().Property(e => e.C_Id).HasColumnAnnotation("Index", 
    new IndexAnnotation(new IndexAttribute("IX_BC", 2) { IsUnique = true }));

Upvotes: 1

Related Questions