asp.net-mvc 是否可以使用 Entity Framework Code First 设置唯一约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26837800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to set a unique constraint using Entity Framework Code First?
提问by subi_speedrunner
I want to enforce Unique constraint in a table & I am using Entity Framework Code-First.
我想在表中强制执行唯一约束,我正在使用实体框架代码优先。
Is it possible to add a unique constraint using EF 6 as i believe in earlier versions it was not possible.
是否可以使用 EF 6 添加唯一约束,因为我相信在早期版本中这是不可能的。
回答by SBirthare
It appears that the unique constraint featurethat was scheduled to release with Version 6 got pushed to 6.1.
计划在版本 6 中发布的独特约束功能似乎被推送到 6.1。
With EF 6.1, you can define a constraint using the Index attribute as shown below:
使用 EF 6.1,您可以使用 Index 属性定义约束,如下所示:
[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }
[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }
OR
或者
You can use Fluent API as shown here in MSDN
您可以使用 Fluent API,如MSDN 中所示
回答by Hassen Ch.
Let's say that you want to add the Unique constraint on only one attribute, you can do as following, starting from EF6.1
假设您只想在一个属性上添加唯一约束,您可以从 EF6.1 开始执行以下操作
[Index(IsUnique = true)]
public string Username { get; set; }
If you have multiple fieldsthat are related to the same index then you are going to use:
如果您有多个与同一索引相关的字段,那么您将使用:
Multiple-Column Indexes
Indexes that span multiple columns are specified by using the same name in multiple Index annotations for a given table. When you create multi-column indexes, you need to specify an order for the columns in the index. For example, the following code creates a multi-column index on Rating and BlogId called IX_BlogAndRating. BlogId is the first column in the index and Rating is the second.
多列索引
通过在给定表的多个索引注释中使用相同的名称来指定跨越多个列的索引。创建多列索引时,需要为索引中的列指定顺序。例如,以下代码在 Rating 和 BlogId 上创建了一个名为 IX_BlogAndRating 的多列索引。BlogId 是索引中的第一列,Rating 是第二列。
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[Index("IX_BlogIdAndRating", 2)]
public int Rating { get; set; }
[Index("IX_BlogIdAndRating", 1)]
public int BlogId { get; set; }
}
Please refer to this linkfor further information.
请参阅此链接以获取更多信息。

