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 设置唯一约束?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
