-2

I'm use Entityframework Code First, and an EntityTypeConfiguration using fluent API. how can create Unique Constraint with multi column. for example i have a table with below field

  • Id
  • CompanyId
  • Code
  • Name

i want set Code column to unique , per CompanyId

A.R
  • 3
  • 2
  • Please provide example data rather than just bullet point fields. Also please show us what you have tried so far – Bendy Jun 30 '15 at 06:11

1 Answers1

3

In your EntityTypeConfiguration you can do something like this:

Property(m => m.CompanyId)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_YourUniqueIndexName", 1) { IsUnique = true }));
Property(m => m.Code)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_YourUniqueIndexName", 2) { IsUnique = true }));

This will create a unique index on those 2 columns.

Make sure you use the same name for the unique index. Both need to be name "IX_YourUniqueIndex". If one is called "IX_Index1" and the other "IX_Index2" then it will create a unique index on each, which is not what you want

Black_bull
  • 65
  • 6
Florian Haider
  • 1,892
  • 18
  • 23