how can create Unique Constraint with multi column with entityframework

你离开我真会死。 提交于 2019-12-25 18:59:06

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/31130642/how-can-create-unique-constraint-with-multi-column-with-entityframework

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