Setting unique Constraint with fluent API?
On EF6.2, you can use HasIndex()
to add indexes for migration through fluent API.
https://github.com/aspnet/EntityFramework6/issues/274
Example
modelBuilder
.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
On EF6.1 onwards, you can use IndexAnnotation()
to add indexes for migration in your fluent API.
http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex
You must add reference to:
using System.Data.Entity.Infrastructure.Annotations;
Basic Example
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()));
Practical Example:
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 }));
Entity Framework unique key with fluent api?
In Entity Framework >= 6.2,
In DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<RecordType>().HasIndex(u => u.RecordType).IsUnique();
}
In Entity Framework < 6.2
In DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<RecordType>().Property(t => t.RecordType).HasMaxLength(1)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_RecordType"){IsUnique = true}));
}
Or in a separate configuration file:
public class RecordTypeConfiguration : EntityTypeConfiguration<RecordType>
{
public RecordTypeConfiguration()
{
HasKey(i => i.Id);
Property(e => e.RecordType).HasColumnType("VARCHAR").HasMaxLength(1);
Property(t => t.RecordType).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_RecordType"){IsUnique = true}));
}
}
Entity Framework Core add unique constraint code-first
On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.
Like this inside your {Db}Context.cs
:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
}
...or if you're using the overload with the buildAction:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>(entity => {
entity.HasIndex(e => e.Email).IsUnique();
});
}
You can read more about it here : Indexes
EF Code First Fluent API define unique constraint
I have this problem occurred before
it can not implement unique constrain using fluent API。
so, the way you used is correct!
Creating Unique Index with Entity Framework 6.1 fluent API
NOTE: Relevant to EF 6
You can use IndexAttribute
as mentioned but with Fluent API
instead of DataAnnotations
which will do the trick:
modelBuilder
.Entity<Person>()
.Property(t => t.Name)
.HasColumnAnnotation(
"Index",
new IndexAnnotation(new IndexAttribute("IX_Name") { IsUnique = true }));
Unfortunately there is no other way to create unique indexes using Fluent API
. There is an open issue regarding this feature: Unique Constraints (Unique Indexes)
UPDATE: Entity Framework Core
In the latest EF Core release you can rely on
Fluent API
to specify indexes without additional tricks. HasIndex
allows to define it:modelBuilder
.Entity<Person>()
.HasIndex(x => x.Name);
Hence it returs IndexBuilder
object you can use it for further index configurations (i.e uniqueness):
modelBuilder
.Entity<Person>()
.HasIndex(x => x.Name)
.IsUnique();
Create Unique constraint for 'true' only in EF Core
You can specify index filter using the HasFilter
fluent API.
Unfortunately it's not database agnostic, so you have to use the target database SQL syntax and actual table column names.
For Sql Server it would be something like this:
.HasIndex(e => new { e.RecordId, e.IsPrimary })
.IsUnique()
.HasFilter("[IsPrimary] = 1");
or
.HasIndex(e => new { e.RecordId, e.IsPrimary })
.IsUnique()
.HasFilter($"[{nameof(RecordAttachment.IsPrimary)}] = 1");
For more information, see Relational Database Modeling - Indexes documentation topic.
Unique Key constraints for multiple columns in Entity Framework
With Entity Framework 6.1, you can now do this:
[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }
[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }
The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN
Related Topics
Getting Overlapping Regex Matches in C#
How to Programmatically Click a Button in Wpf
How to Install a Certificate into the Local MAChine Store Programmatically Using C#
Using the C# Dispatcher in Wpf Applications
Md5 Hash with Salt for Keeping Password in Db in C#
How to Use Webbrowser Control Documentcompleted Event in C#
Openxml Sdk Returning a Number for Cellvalue Instead of Cells Text
Formatting a Double to Two Decimal Places
Windows Forms Designer and Wpf Designer for .Net Core
How to Draw a Rounded Rectangle as the Border for a Rounded Form
Mongodb Gridfs with C#, How to Store Files Such as Images
What's the Difference Between Anonymous Methods (C# 2.0) and Lambda Expressions (C# 3.0)
How to Create an Expression Tree to Represent 'String.Contains("Term")' in C#
How to Get Urls of Open Pages from Chrome and Firefox
How to Pass a Single Object[] to a Params Object[]
How to Round Up Value C# to the Nearest Integer
Wpf Databinding to Interface and Not Actual Object - Casting Possible