0

I need to create a POCO that has multiple fields that are unique. I have the typical Entity Id field marked with Key. But I have another field named StudentId which is of type string and needs to be unique also. Using [Key] attribute on multiple fields including the Id throws an error. I can't find any other attribute that does the job. Please help me, thanks.

Randal Cunanan
  • 2,449
  • 6
  • 29
  • 38
  • See [http://stackoverflow.com/questions/10614575/entity-framework-code-first-unique-column](http://stackoverflow.com/questions/10614575/entity-framework-code-first-unique-column) for how to mark column as unique using data annotation. – grabbag Jan 21 '17 at 22:13

1 Answers1

2

Have you tried doing this in the CreateIndex method?

CreateIndex(table: "Students", 
        column: "Name", 
        unique: true, // unique index
        name: "StudentIndex");

You could also try it using the ExecuteStoreCommand

context.ObjectContext.ExecuteStoreCommand("CREATE UNIQUE CONSTRAINT...");
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
  • Thanks, I just thought there is an attribute that can handle that. – Randal Cunanan Jul 29 '13 at 04:14
  • @RueLeonheart No there isn't but you can show your support for it being added in the next version by [voting for it here](http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2231176-indexattribute) – Scott Chamberlain Jul 29 '13 at 04:57
  • I don't have the time to look now, but I'm sure there should be a way to wire up your own attribute and call it `[IndexAttribute]` whereby you can trigger the `CreateIndex` command. – Chase Florell Jul 29 '13 at 16:56
  • Or maybe a clearer attribute might be `[CreateIndex]` with `public void CreateIndexAttribute(..){..}` – Chase Florell Jul 29 '13 at 18:59