Составной уникальный индекс

#c# #entity-framework #composite-key #ef-fluent-api

#c# #entity-framework #составной ключ #ef-fluent-api

Вопрос:

у меня есть следующие модели, я хочу указать с помощью FluentAPI, что пара в таблице A, B.Id и C.Id являются уникальными

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

Комментарии:

1. Если комбинация B и C уникальна, вам действительно нужен Id?

Ответ №1:

Это невозможно только с навигационными свойствами.

Необходимо добавить явные поля FK:

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

и создайте уникальный индекс, используя следующую свободную конфигурацию API:

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