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 设置唯一约束?
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
