[英]DataAnnotation [Index(IsUnique = true)] on a column throws error Attribute 'Index' is not valid on this declaration type
This is my first time exploring DataAnnotations (I was hoping to use this over fluent)...and I don't understand why the following code throws a compile time error:这是我第一次探索 DataAnnotations(我希望能够流畅地使用它)......我不明白为什么下面的代码会引发编译时错误:
CS0592 - Attribute 'Index' is not valid on this declaration type. CS0592 - 属性“索引”在此声明类型上无效。 It is only valid on 'class' declaration
它仅对“类”声明有效
public class Holiday
{
[Key]
public int Id { get; set; }
[Required]
[Index(IsUnique = true)]
public DateTime? Date { get; set; }
public string Name { get; set; }
}
My goal is to make the Date
column UNIQUE...and I thought using [Index(IsUnique = true)]
on a column is the correct way to make it unique...but it is not allowing me to use the Index attribute on columns, only on classes...我的目标是使
Date
列唯一...我认为在列上使用[Index(IsUnique = true)]
是使其唯一的正确方法...但它不允许我使用 Index 属性列,仅在类...
Please teach me how to achieve this?请教我如何实现这一目标?
Well, the Index
attribute is the data annotation equivalent of HasIndex
fluent API, and simlar to the API, is intended to be applied at entity (class) level, providing the properties which constitute the index, in order , plus other information like the index name, whether it is unique etc.好吧,
Index
属性是HasIndex
fluent API 的数据注释等价物,与 API 类似,旨在应用于实体(类)级别,提供构成索引的属性,按顺序,加上索引等其他信息名称,是否唯一等。
So in your case you'd need something like this所以在你的情况下,你需要这样的东西
[Index(nameof(Holiday.Date), IsUnique = true)]
public class Holiday
{
// ...
}
which corresponds to the following fluent configuration对应于以下流畅的配置
modelBuilder.Entity<Holiday>()
.HasIndex(e => e.Date)
.IsUnique();
Actually all this is well explained with examples in the Indexes section of the official EF Core documentation.实际上,所有这些都通过官方 EF Core 文档的索引部分中的示例进行了很好的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.