Setting unique Constraint with fluent API?(使用流畅的 API 设置唯一约束?)
问题描述
我正在尝试使用 Code First 构建一个 EF 实体,并使用流式 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()
在 fluent 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
您必须添加参考:
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.FirstName
和User.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 }));
这篇关于使用流畅的 API 设置唯一约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用流畅的 API 设置唯一约束?


- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01