Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity Framework 5 support unique constraints?

Wondering if Entity Framework 5 supports unique constraints on entity properties? If so, how can I specify that a property should be unique?

like image 963
aknuds1 Avatar asked Aug 05 '12 20:08

aknuds1


People also ask

What is the difference between unique index and unique constraint?

A constraint has different meaning to an index. It gives the optimiser more information and allows you to have foreign keys on the column, whereas a unique index doesn't.

What is the purpose of a unique constraint?

The Unique constraint is a column constraint used to ensure unique values in the column. It prevents duplicate values from appearing in a column for two or more rows.

What is unique constraint in SQL Server?

The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint.


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

http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-i-e-candidate-key-support

...because apparently it isn't even on the roadmap for EF 6.0 at the moment:

http://entityframework.codeplex.com/wikipage?title=Roadmap

like image 106
Slauma Avatar answered Oct 22 '22 13:10

Slauma


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.

like image 37
Vova Bilyachat Avatar answered Oct 22 '22 14:10

Vova Bilyachat