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

时间:2014-10-09 04:06:26

标签: c# entity-framework ef-fluent-api

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

  2. 我喜欢在我的所有表格中始终使用自动增量作为主键。

  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");
    
  4. 如何在Fluent API中实现此复合唯一性?

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用&#39; HasColumnAnnotation(...)&#39;来实现此目的。方法和应用IndexAnnotation&gt; IndexAttribute。

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

您可以找到更多信息here (MSDN)

答案 1 :(得分:1)

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

我会接受Aydin的答案。

相关问题