[英]EF Fluent API + two column composite uniqueness + autoincrement primary key
我使用Fluent API。 我不喜欢注释。
我喜欢在所有表中始终使用自动增量作为主键。
我的一些表需要两个列,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`)
);
Aydin的答案有概念( IndexAnnotation
和HasColumnAnnotation
),但它没有涉及其他列。 这是一个对我有用的完整答案:
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.