问题描述
我有一个列必须是unqiue的名称。没有外键或任何类似的东西。
I have a column "Name" that must be unqiue. No foreign key or anything like that.
EF 6.1最后支持通过注释创建这样的索引。已经在SO上讨论过了。但是,它似乎只能通过类中的注释来完成。如何仅使用Fluent API?
EF 6.1 finally supports creating such indexes via Annotations. That has been discussed already on SO. But it seems it can only be done via annotations in the classes. How do I do that using only the Fluent API?
这样做:
public class PersonConfiguration : EntityTypeConfiguration<Person>
{
public PersonConfiguration()
{
HasKey(p => p.Id);
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//not possible?
Index(p => p.Name).IsUnique(); //???
}
}
推荐答案
你可以使用 IndexAttribute
,但是,而不是 DataAnnotations
这将是诀窍:
You can use IndexAttribute
as mentioned but with Fluent API
instead of DataAnnotations
which will do the trick:
modelBuilder
.Entity<Person>()
.Property(t => t.Name)
.HasColumnAnnotation(
"Index",
new IndexAnnotation(new IndexAttribute("IX_Name") { IsUnique = true }));
不幸的是,没有其他方法可以使用 Fluent API
。关于此功能有一个开放的问题:
Unfortunately there is no other way to create unique indexes using Fluent API
. There is an open issue regarding this feature: Unique Constraints (Unique Indexes)
这篇关于使用实体框架创建唯一索引6.1流畅的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!