创建具有实体框架6.1流利的API唯一索引 [英] Creating Unique Index with Entity Framework 6.1 fluent API

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

问题描述

我有一列名称必须是独特之。没有外键之类的东西。

I have a column "Name" that must be unqiue. No foreign key or anything like that.

EF 6.1终于支持通过注释创建这样的索引。这已被讨论了SO。但现在看来,这只能通过在类注释进行。我如何做,只用流利的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 中提到,但的流利的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 }));

不幸的是没有其他办法使用流利的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唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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