我有以下型号,我想使用FluentApi指定表A,B.Id和C.Id中的paire是唯一的
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; }
}
答案 0 :(得分: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; }
}
并使用以下Fluent 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 }));