Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique keys in Entity Framework 4

An existing DB schema has unique, non-primary, keys, and some foreign keys that rely on them.

Is it possible to define unique keys, which are not primary keys, in Entity Framework v4? How?

like image 221
Asaf R Avatar asked Apr 10 '10 20:04

Asaf R


People also ask

Can a table have 2 unique keys?

Yes a table can have n number of unique and foreign keys. Unique key constraints are used to ensure that data is not duplicated in two rows in the database. One row in the database is allowed to have null for the value of the unique key constraint.

Can unique keys be multiple?

Multiple unique keys can present in a table. NULL values are allowed in case of a unique key. These can also be used as foreign keys for another table.

How do I find a unique key?

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.


2 Answers

The Entity Framework 6.1 now supports uniques with both Data Annotations and Fluent API.

Data Annotations (Reference)

public class MyEntityClass
{ 
    [Index(IsUnique = true)]
    [MaxLength(255)] // for code-first implementations
    public string MyUniqueProperty{ get; set; } 
}

Fluent API (Reference)

public class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder 
                .Entity<MyEntityClass>() 
                .Property(t => t.MyUniqueProperty) 
                .HasMaxLength(255) // for code-first implementations
                .HasColumnAnnotation( 
                    "Index",  
                    new IndexAnnotation(new[] 
                        { 
                            new IndexAttribute("Index") { IsUnique = true } 
                        })));
        }
    }
}

You have to apply an index and set the unique property to true. By default, indexes are non-unique according to documentation.

And also you have to install the Entity Framework 6.1 NuGet package in your project in order to use the new API for indexes.

Note about code-first implementations: A VARCHAR(MAX) cannot be part of a unique constraint. You must specify the maximum length either as a Data Annotation or in the Fluent API.

like image 175
Evandro Pomatti Avatar answered Sep 19 '22 06:09

Evandro Pomatti


See also this MSDN blog post: http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx. In brief, this isn't supported in V4, though the EF team seems to have plans to support it in future releases.

like image 33
Ken Smith Avatar answered Sep 18 '22 06:09

Ken Smith