实体框架核心先添加唯一约束代码 [英] Entity Framework Core add unique constraint code-first

查看:74
本文介绍了实体框架核心先添加唯一约束代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到使用属性向字段添加唯一约束的方法:

I can't find way to add a unique constraint to my field with using attribute:

public class User
{
    [Required]
    public int Id { get; set; }

    [Required]
    // [Index("IX_FirstAndSecond", 2, IsUnique = true)] not supported by core
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }
}

我正在使用以下软件包:

I'm using these packages:

 "Microsoft.EntityFrameworkCore": "1.0.1",
 "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
 "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1",
 "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",


推荐答案

在EF内核上,不能使用数据注释创建索引。但是可以使用Fluent API来创建索引。

On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.

在您的 {Db} Context.cs $ 中:

Like this inside your {Db}Context.cs:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<User>()
        .HasIndex(u => u.Email)
        .IsUnique();
}

...或者如果在buildAction中使用重载: / p>

...or if you're using the overload with the buildAction:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<User>(entity => {
        entity.HasIndex(e => e.Email).IsUnique();
    });
}

您可以在此处了解更多信息: 索引

You can read more about it here : Indexes

这篇关于实体框架核心先添加唯一约束代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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