簡體   English   中英

EF Fluent API +兩列復合唯一性+自動增量主鍵

[英]EF Fluent API + two column composite uniqueness + autoincrement primary key

  1. 我使用Fluent API。 我不喜歡注釋。

  2. 我喜歡在所有表中始終使用自動增量作為主鍵。

  3. 我的一些表需要兩個列,X和Y(其中X不是自動增量鍵而Y不是自動增量鍵)必須是唯一的,即:不能有另一行,使得它具有X1 = X2和Y1 = Y2。 如果我沒有使用自動增量鍵,我只需將這兩個鍵作為鍵,如下所示:

      modelBuilder.Entity<Foo>() .HasKey(t => new { tX, tY }) .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`) 
);

您可以使用'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))

我會接受Aydin的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM