EF Core 中是否有唯一约束的数据注释(代码优先)? [英] Is there a data annotation for unique constraint in EF Core (code first)?
问题描述
我想知道 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 中,您可以流畅地使用扩展方法 HasAlternateKey
仅限 API.没有没有数据注释来实现唯一约束.
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中,您可以使用fluent API的扩展方法HasIndex
或带有[Index]
属性的数据注解方式.
Also it's possible to define an unique index. Therefore, in EF Core you can use the fluent API's extension method HasIndex
or the data annotation way with the attribute [Index]
.
在这篇 MS 文档文章中 - 索引 - 你将找到更多信息如何使用.
In this MS doc article - Indexes - you will find further information how to use.
以下是具有 fluent API 的唯一索引示例:
Here an example for an unique index with fluent API:
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; }
}
这里是相同的例子,但带有数据注释:
Here the same example, but with data annotation:
[Index(nameof(Url), IsUnique = true)]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
更新 2021-09-10
- 添加了如何与数据注释一起使用的附加信息,因为它现在在 EF Core 中可用;
更新 2021-09-24
- 修复了属性示例中缺少的 IsUnique 属性
这篇关于EF Core 中是否有唯一约束的数据注释(代码优先)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!