如何在配置文件中的EF中放置唯一密钥约束

本文关键字:唯一 密钥 约束 配置文件 EF | 更新日期: 2023-09-27 18:27:54

我在带有配置文件的项目中使用EF。我有Employee的域类,它只有它的属性(没有数据注释或任何关系)

我想为用户名编写唯一的密钥约束代码。

请看下面的员工类。

public class Employee : IEntity
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public string Address { get; set; }
    public string MobileNo { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

我有一个配置类,它包含了employee类的所有验证。

using System.Data.Entity.ModelConfiguration;
class Configurations
{
    public class EmployeeConfigration : EntityTypeConfiguration<Employee>
    {
        public EmployeeConfigration()
        {
            this.Property(x => x.FirstName).IsRequired().HasMaxLength(50);
            this.Property(x => x.LastName).HasMaxLength(50);
            // I want to write code for unique key constrain,for username property. 
        }
    }
}

如何编写username属性的唯一密钥约束?

如何在配置文件中的EF中放置唯一密钥约束

请尝试此代码

using System.ComponentModel.DataAnnotations.Schema; 
using System.Data.Entity.Infrastructure.Annotations;
...

this.Property(t => t.UserName) 
    .HasColumnAnnotation(
       IndexAnnotation.AnnotationName, 
       new IndexAnnotation(
           new IndexAttribute("IX_UserName", 1) { IsUnique = true }));

EDIT:使用语句添加

EF不支持唯一约束,但支持唯一索引。使用fluent API无法直接映射它们,但您可以使用fluent API方法添加属性,如下所示。

Property(x => x.UserName)
.HasColumnAnnotation("Index", new IndexAttribute() {IsUnique = true});

编辑

正如Max Brodin在评论中指出的那样,这只在EF 6.1时得到支持。