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

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

问题描述

我正在尝试使用 Code First 构建一个 EF 实体,并使用 fluent 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.2 上,可以使用 HasIndex() 添加索引以通过 fluent API 进行迁移.

On EF6.2, you can use HasIndex() to add indexes for migration through fluent API.

https://github.com/aspnet/EntityFramework6/issues/274

示例

modelBuilder
    .Entity<User>()
    .HasIndex(u => u.Email)
        .IsUnique();

EF6.1 之后,您可以使用 IndexAnnotation() 在流畅的 API 中添加用于迁移的索引.

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

http://msdn.microsoft.com/en-us/数据/jj591617.aspx#PropertyIndex

您必须添加对以下内容的引用:

You must add reference to:

using System.Data.Entity.Infrastructure.Annotations;

基本示例

这里有一个简单的用法,在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.FirstNameUser.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 }));

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

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