使用 Entity Framework 联合复合时使两列唯一

Making two columns unique when jointly compounded using Entity Framework

我有两个专栏,名为 MonkeyDonkey。两者都是非空的,即 null 是不允许的。设置声明如下。

protected override void OnModelCreating(ModelBuilder builder)
{
  base.OnModelCreating(builder);
  ...
  builder.Entity<Thing>()
    .Property(a => a.Monkey)
    .IsRequired();
  builder.Entity<Thing>()
    .Property(a => a.Donkey)
    .IsRequired();
}

现在,我了解到组合的内容必须是唯一的,即没有记录可能具有相同的猴子和驴子。根据 MSDN (index on multiple props), I'm supposed to use HasColumnAnnotation and pass an instance of IndexAnnotation. It's also suggested in System.Data.Entity.Infrastructure.Annotations.

使用 IndexAnnotation.AnnotationName

问题是我找不到那个方法,而是只看到 HasAnnotation。我不清楚它是否是更新的版本(因为链接到的 post 现在有点过时了)。我无法在 using 语句中访问命名空间 Entity,也无法访问。

builder.Entity<Thing>()
  .Property(a => a.Monkey)
  .HasAnnotation(...);

这是正确的方法还是我应该继续寻找其他注释方法?获取命名空间缺少什么?索引是否是合适的开始方式?

我也尝试使用索引,但这需要我声明一个专门的 class,这看起来很笨重,表明这是错误的方法。

builder.Entity<Thing>()
  .HasIndex(a => new IndexDedicatedClass(a.Monkey, a.Donkey))
  .IsUnique();

您可以添加一个跨多个列的复合索引,然后将其标记为唯一,这会在数据库上创建一个唯一索引。

modelBuilder.Entity<Thing>(builder =>
{
    builder
        .HasIndex(e => new { e.Monkey, e.Donkey })
        .IsUnique();
});

这实际上有助于确保 ($monkey, $donkey) 元组不会在 table 中出现两次。

更多信息