简体   繁体   中英

How to put unique key constrain in EF ,in configuration file?

I am using an EF in project with configuration file. I have domain class of Employee which have only its properties( No Data Annotations or any relation)

I want to write unique key constrain code for username.

Please look at below , the employee class.

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; }
}

I have configuration class, which contains all the validations of employee class.

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. 
        }
    }
}

How can I write the unique key constrain for username property ?

Please try this code

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: added using statement

EF doesn't support Unique constraints, but it does support unique indexes. There is no direct way of mapping them with the fluent API, but you can leverage the fluent APIs method of adding attributes as below.

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

EDIT

As Max Brodin pointed out in his comment, this is only supported as of EF 6.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM