简体   繁体   中英

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:

CS0592 - Attribute 'Index' is not valid on this declaration type. 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...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM