Goran
Goran

Reputation: 6518

EF CodeFirst Validation of Unique composite key

I have a table that contains an Id column as a primary key. There is also a requirement to enforce uniqueness on two other columns, which are actually FKs. In Sql Server I can create a UniqueKey on this two columns.

What can I do on the EF side so that it can validate uniqueness over these two fields?

Upvotes: 1

Views: 1204

Answers (2)

marvc1
marvc1

Reputation: 3689

In your POCO class mark each column that needs to be unique as Key. As in:

public MyPocoClass {
   [Key, Column(Order = 0)]
   public int Id { get; set; }

   [Key, Column(Order = 1)]
   public int Col2name { get; set; }


   [Key, Column(Order = 2)]
   public int Col3name { get; set; }
}

Setting the Column order is useful so that your primary key columns are all displayed together in the sql db.

If the columns are Foreign keys to other Entity Framework code first classes then simply name the property as tablename_tableId and EF will do the rest. I.e

public anotherClass {
       public int Id { get; set; }

       public int MyPocoClass_Id { get; set; } //this is a foreign key

    }

Upvotes: -1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

EF doesn't support unique keys so your best workaround is to use unique key in the database and catch exception during saving. If you need EF to create the unique key during database creation you can use custom initializer.

If you want to have some validation in the application you will need to execute some query and check that these data don't exist yet but you will still need to use the former advice with catching exception because another thread / process / user can create such data between your query and saving changes.

Upvotes: 2

Related Questions