Wondering if Entity Framework 5 supports unique constraints on entity properties? If so, how can I specify that a property should be unique?
-
1No. But it is [since Entity Framework 6.1](http://stackoverflow.com/a/23378448/3231778). – Evandro Pomatti Aug 01 '14 at 15:57
5 Answers
No, it doesn't. There were plans in the past to include a unique constraint feature in EF 5.0:
http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx
But you can see that there is an update on top of the post:
Update: this feature has been postponed and will not be included in Entity Framework 5.
You can vote on the feature to raise possibly the priority it gets implemented with...
...because apparently it isn't even on the roadmap for EF 6.0 at the moment:

- 175,098
- 59
- 401
- 420
Well i was looking for solution and finally i found it. when you generate migration in code you can create unique key
CreateTable(
"dbo.TaBLE",
c => new
{
Id = c.Int(nullable: false, identity: true),
Date = c.DateTime(nullable: false),
Meter_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.Index(t => new {t.Meter_Id, t.Date}, true);
Validation before insert you can do on BLL level, so i think it can solve your problem.

- 18,765
- 4
- 55
- 80
While unique constraints are still not supported out of the box by EF (version 6.0 as of writing this), there are some workarounds for Code First approach to get the desired behaviour. See an attribute-based solution, as an answer to a similar question. Works with EF 5.0+.
EDIT:
Starting with EF 6.1 unique indexes are supported:
[Index(IsUnique = true)]
public string EmailAddress { get; set; }
They are the same as the unique constraints for most practical purposes.

- 1
- 1

- 2,162
- 1
- 20
- 15
As mentioned above it is not supported but as for now when I create a database programmatically (Code First) I use the following code in the init db section:
MainDBContext mainDBContext = new MainDBContext();
mainDBContext.Database.ExecuteSqlCommand("ALTER TABLE table_name ADD CONSTRAINT uc_FieldName UNIQUE(FieldName)");
mainDBContext.Dispose();

- 10,722
- 2
- 45
- 46
I found a work-around in order to achieve unique constraints on entity properties. It's really and intuitive. Please refer to my other post:

- 1
- 1

- 2,032
- 3
- 27
- 35