Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code first : Set unique key constraint is not working

In my application I am using EntityFramework with code first approach. I am using EF7 with ASP.NET 4.6 MVC and VS2015. My model class is like below :

public class Customer
{
    public int CustomerID { get; set; }

    [StringLength(100)]
    [Required]
    public string FirstName { get; set; }

    [StringLength(100)]
    [Required]
    public string LastName { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Please enter valid Email Address.")]
    [StringLength(100)]
    [Index("IX_EA", IsUnique = true)]
    public string EmailAddress { get; set; }

}

My context file is like below :

public class CustomerContext : DbContext
{
    public CustomerContext()
    {
        Database.EnsureCreated();
    }
    public DbSet<Customer> Customers { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {    
        var connection = System.Configuration.ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
        options.UseSqlServer(connection).UseRowNumberForPaging();
    }
}

So, from model class you can see that I want set unique constraint to EmailAddress column in database table means EmailAddress field should contain duplicate value(an email address should not be repeat in table). But when I run the project database successfully get created. but that Unique constraint in not there. I am not getting why it is not setting that constraint on EmailAddress field.

Please help me to set unique constraint to the field using code first approach of EntityFramework.

like image 293
iDipa Avatar asked Sep 11 '26 11:09

iDipa


1 Answers

From EF Core Documentation:

Indexes can not be created using data annotations.

But you can use the fluent API to create index :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .HasIndex(c => c.EmailAddress) // Create an index
        .IsUnique() // that is unique
        .ForSqlServerHasName("IX_EA"); // specify the name 
}

You can also use Alternate keys

An alternate key serves as a alternate unique identifier for each entity instance in addition to the primary key. When using a relational database this maps to the concept of a unique index/constraint. In EF, alternate keys provide greater functionality than unique Indexes because they can be used as the target of a foreign key.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .HasAlternateKey(c => c.EmailAddress);
}
like image 81
Thomas Avatar answered Sep 13 '26 01:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!