设置用流利的API唯一约束? [英] Setting unique Constraint with fluent API?

查看:166
本文介绍了设置用流利的API唯一约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用code构建一个EF实体首先,用流利的API一个 EntityTypeConfiguration 。创建主键很容易,但并非如此具有唯一约束。我看到所建议的这个执行本地SQL命令旧文章,但似乎打败的目的。这可能与EF6?

I'm trying to build an EF Entity with Code First, and an EntityTypeConfiguration using fluent API. creating primary keys is easy but not so with a Unique Constraint. I was seeing old posts that suggested executing native SQL commands for this, but that seem to defeat the purpose. is this possible with EF6?

推荐答案

EF6.1 起,您可以使用 IndexAnnotation()来加移民索引您流畅的API中。

On EF6.1 onwards, you can use IndexAnnotation() to add indexes for migration in your fluent API.

<一个href=\"http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex\">http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex

您必须添加引用:

using System.Data.Entity.Infrastructure.Annotations;

Basic范例

下面是一个简单的使用量,增加对 User.FirstName 属性的索引

Here is a simple usage, adding an index on the User.FirstName property

modelBuilder 
    .Entity<User>() 
    .Property(t => t.FirstName) 
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));

实例:

下面是一个更现实的例子。它在多个属性将唯一索引 User.FirstName User.LastName ,与索引名IX_FIrstNameLastName

Here is a more realistic example. It adds a unique index on multiple properties: User.FirstName and User.LastName, with an index name "IX_FIrstNameLastName"

modelBuilder 
    .Entity<User>() 
    .Property(t => t.FirstName) 
    .IsRequired()
    .HasMaxLength(60)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(
            new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));

modelBuilder 
    .Entity<User>() 
    .Property(t => t.LastName) 
    .IsRequired()
    .HasMaxLength(60)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(
            new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));

这篇关于设置用流利的API唯一约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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