使用 Entity Framework 6.1 fluent API 创建唯一索引 [英] Creating Unique Index with Entity Framework 6.1 fluent API

查看:14
本文介绍了使用 Entity Framework 6.1 fluent API 创建唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列名称"必须是唯一的.没有外键或类似的东西.

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();  //???
    }
}

推荐答案

注意:与 EF 6 相关

您可以使用上述的 IndexAttribute使用 Fluent API 而不是 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)

<小时>更新:实体框架核心

在最新的 EF Core 版本中,您可以依赖 Fluent API 来指定索引 没有额外的技巧.
HasIndex 允许定义它:


UPDATE: Entity Framework Core

In the latest EF Core release you can rely on Fluent API to specify indexes without additional tricks.
HasIndex allows to define it:

modelBuilder 
    .Entity<Person>()
    .HasIndex(x => x.Name);

因此它返回 IndexBuilder 对象,您可以将其用于进一步的索引配置(即唯一性):

Hence it returs IndexBuilder object you can use it for further index configurations (i.e uniqueness):

modelBuilder 
    .Entity<Person>()
    .HasIndex(x => x.Name)
    .IsUnique();

这篇关于使用 Entity Framework 6.1 fluent API 创建唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆