简体   繁体   English

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

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

  1. I use Fluent API. 我使用Fluent API。 I don't like annotations. 我不喜欢注释。

  2. I like to always use an autoincrement as my primary key, in all of my tables. 我喜欢在所有表中始终使用自动增量作为主键。

  3. Some of my tables require that two columns, X and Y (where X is not the autoincrement key and Y is not the autoincrement key) have to be unique, ie: there can't be another row such that it has X1=X2 and Y1=Y2. 我的一些表需要两个列,X和Y(其中X不是自动增量键而Y不是自动增量键)必须是唯一的,即:不能有另一行,使得它具有X1 = X2和Y1 = Y2。 If I wasn't using an autoincrement key, I would simply make these two the key, like this: 如果我没有使用自动增量键,我只需将这两个键作为键,如下所示:

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

    But, as I said in (2), I'm using autoincrement primary keys 但是,正如我在(2)中所说,我正在使用自动增量主键

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

How can I achieve this composite uniqueness in Fluent API? 如何在Fluent API中实现这种复合唯一性?

This is what I want to achieve, written in SQL: 这是我想用SQL编写的:

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

You can achieve this using the 'HasColumnAnnotation(...)' method and applying an IndexAnnotation > IndexAttribute. 您可以使用'HasColumnAnnotation(...)'方法并应用IndexAnnotation> IndexAttribute来实现此目的。

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

You can find further information here (MSDN) 您可以在此处找到更多信息(MSDN)

Aydin's answer had the concept ( IndexAnnotation and HasColumnAnnotation ) but it wasn't involving the other columns. Aydin的答案有概念( IndexAnnotationHasColumnAnnotation ),但它没有涉及其他列。 Here is a complete answer that worked for me: 这是一个对我有用的完整答案:

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

That, supposing that X is string column and Y is not (just to show how .HasMaxLength(60) can be used in the string column) 假设X是字符串列而Y不是(只是为了显示如何在字符串列中使用.HasMaxLength(60))

I will accept Aydin's answer though. 我会接受Aydin的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM