Does Entity Framework 5 support unique constraints?

走远了吗. 提交于 2019-11-28 09:43:40

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

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.

Mihkel Müür

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.

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();
Mirel Vlad

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:

https://stackoverflow.com/a/16496291/1873113

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!