如何创建带有实体框架的多列的唯一约束 [英] how can create Unique Constraint with multi column with entityframework

查看:49
本文介绍了如何创建带有实体框架的多列的唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我先使用Entityframework Code,然后使用fluent API进行EntityTypeConfiguration.如何创建具有多列的唯一约束.例如,我有一个带有以下字段的表

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

  • 编号
  • CompanyId
  • 代码
  • 名称

我想将每个CompanyId的代码列设置为unique

i want set Code column to unique , per CompanyId

推荐答案

在EntityTypeConfiguration中,您可以执行以下操作:

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.

确保唯一索引使用相同的名称.两者都必须命名为"IX_YourUniqueIndex".如果一个叫做"IX_Index1",另一个叫做"IX_Index2",那么它将在每个名字上创建一个唯一的索引,这不是您想要的

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

这篇关于如何创建带有实体框架的多列的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆