EF Core中是否存在用于唯一约束的数据注释(代码优先)? [英] Is there a data annotation for unique constraint in EF Core (code first)?

查看:412
本文介绍了EF Core中是否存在用于唯一约束的数据注释(代码优先)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Entity Framework Core 2代码优先方法中是否存在用于唯一约束的数据注释?

I am wondering if there is a data annotation for unique constraint in Entity Framework Core 2 code first approach?

推荐答案

在EF Core您只能在流畅的API中使用扩展方法 HasAlternateKey 。没有没有数据注释来实现唯一约束

In EF Core You could use the extension method HasAlternateKey in fluent API only. There are no data annotations to realize a unique constraint.

此MS文档文章-备用键(唯一约束)-将说明如何使用以及哪些

This MS doc article - Alternate Keys (Unique Constraints) - will explain how to use and which further possibilities are exist.

上面链接中的简短示例:

A short example from link above:

class MyContext : DbContext
{
    public DbSet<Car> Cars { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>()
            .HasAlternateKey(c => c.LicensePlate)
            .HasName("AlternateKey_LicensePlate");
    }
}

class Car
{
    public int CarId { get; set; }
    public string LicensePlate { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
}

也可以定义唯一索引 。因此,在EF Core中,您必须在流畅的API中使用扩展方法 HasIndex 无数据注释)。
在此MS文档文章-索引-您会找到更多信息。

Also it's possible to define an unique index. Therefor in EF Core you have to use in fluent API the extension method HasIndex (no data annotations). In this MS doc article - Indexes - you will find further information.

以下是唯一索引的示例:

And here an example for an unique index:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .IsUnique();
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

这篇关于EF Core中是否存在用于唯一约束的数据注释(代码优先)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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