2

Is it possible in Entity Framework 5 to define a property as "Unique" besides the Key?

My Model already has a property "ID" which has the 'Key' attribute. Now I want another prperty to be unique. How can I achieve this?

amaters
  • 2,266
  • 2
  • 24
  • 44
  • 1
    check out http://stackoverflow.com/questions/8262590/entity-framework-code-first-fluent-api-adding-indexes-to-columns which lets you add a unique index. You can add a unicity constraint at the cost of adding an index. – Martijn Aug 05 '13 at 18:09
  • In addition to the above it may be desirable to add the uniqueness check in your business logic for early checking and provide meaningful feedback before you get a Sql Exception. – Jay Aug 05 '13 at 19:03

1 Answers1

4

You cannot do that through EntityFramework, the only possibility is modifying your database.

It's in the pipeline however for EF 6: http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx

Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • Yes, I already found out it is not "out of the box" but surely there has to be a workaround for it right? – amaters Aug 05 '13 at 18:06
  • Yes, by editing your database directly. Since there's no notion of it in EF, there's no way to specify it, not through the FluentAPI, nor with attributes, nor with mappings – Kenneth Aug 05 '13 at 18:07
  • 5
    Migrations allow to add a unique index without editing the db directly. But the result is basically the same - a unique db index and EF's model metadata have no knowledge about it. BTW: Unique constraints won't come with EF 6, it has been postponed again :( – Slauma Aug 05 '13 at 18:36