gpt4 book ai didi

entity-framework - 如何使用数据注释在 EF 7 Code First 中指定唯一键

转载 作者:行者123 更新时间:2023-12-04 01:03:46 25 4
gpt4 key购买 nike

您可以使用 Fluent Api 指定唯一键:

public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }

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

public class User
{
public int UserId { get; set; }
public string Nickname { get; set; }
}

但是您可以使用数据注释来做到这一点吗?

编辑

EF7 Beta 8 中的方法更改:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Index(u => u.Nickname)
.Unique();
}

最佳答案

恐怕要创建一个 Index EF 7 仍不支持使用数据注释。检查此 link .

我还试图在上一个版本中找到与该主题相关的一些信息,但找不到任何内容。

EF 7 beta 8 release notes

EF 7 RC1 release notes

我现在找到了一个 post 来自一位 EF 开发人员 (divega) 说:

In EF7 we support defining indexes using the fluent API but not an attribute, at least no yet. The IndexAttribute you are possibly referring to is something we added to the EF 6.x package at some point but never really became a standard DataAnnotation.

We don't want to copy the original attribute from EF6 as is because there are a few things in it that we would like to change. Also, having it in DataAnnotations directly would likely make more sense than adding it to the EF7 package. I should mention though that it is highly unlikely that we will add IndexAttribute in the EF7 RTM timeframe.



更新 1

显然,这是一项不会添加到 EF Core 的功能,至少目前是这样。

来自 EF Core documentation :

Indexes can not be configured using Data Annotations.



但是你可以使用 Fluent Api 来做到这一点:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasIndex(b => b.Url)
.HasName("Index_Url");
}

关于entity-framework - 如何使用数据注释在 EF 7 Code First 中指定唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com