EF Fluent API+两列复合唯一性+自动递增主键

本文关键字:唯一性 复合 API+ Fluent 两列 EF | 更新日期: 2023-09-27 18:25:57

  1. 我使用Fluent API。我不喜欢注释。

  2. 我喜欢在所有表中始终使用autoincrement作为主键。

  3. 我的一些表要求X和Y这两列(其中X不是自动递增键,Y不是自动递增密钥)必须是唯一的,即:不能有另一行使其具有X1=X2和Y1=Y2。如果我没有使用自动递增密钥,我会简单地将这两个作为密钥,如下所示:

        modelBuilder.Entity<Foo>()
            .HasKey(t => new { t.X, t.Y })
            .ToTable("Foos");
    

    但是,正如我在(2)中所说,我使用的是自动递增主键

        modelBuilder.Entity<Foo>()
            .HasKey(t => t.someLongId)
            .ToTable("Foos");
    

如何在Fluent API中实现这种复合的独特性?

这就是我想要实现的,用SQL:编写

CREATE  TABLE `Foos` (
  `ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT ,
  ...
  PRIMARY KEY (`ID`),
  UNIQUE KEY (`X`, `Y`) 
);

EF Fluent API+两列复合唯一性+自动递增主键

您可以使用"HasColumnAnnotation(…)"方法并应用IndexAnnotation>IndexAttribute来实现这一点。

modelBuilder.Entity<Foo>() 
            .Property(t => t.X) 
            .HasColumnAnnotation("X", new IndexAnnotation(new IndexAttribute("X") { IsUnique = true }));

您可以在这里找到更多信息(MSDN)

Aydin的答案有概念(IndexAnnotationHasColumnAnnotation),但不涉及其他列。以下是一个对我有效的完整答案:
modelBuilder
    .Entity<Foo>()
    .Property(t => t.X)
    .IsRequired()
    .HasMaxLength(60)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_X_Y", 1) { IsUnique = true }));
modelBuilder
    .Entity<Foo>()
    .Property(t => t.Y)
    .IsRequired()
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_X_Y", 2) { IsUnique = true }));

假设X是字符串列,Y不是(只是为了说明如何在字符串列中使用.HasMaxLength(60))

不过我会接受艾丁的回答。