Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say I have the following model:

[Table("Record")]
public class RecordModel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Record Id")]
    public int RecordId { get; set; }

    [StringLength(150)]
    public string Name { get; set; }

    [Required]
    [StringLength(15)]
    public string IMEI { get; set; }
}

Is it possible to add an index to the IMEI column through using an attribute, data annotation, or something from the model?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

EF Core 5

In EF Core 5, the Index attribute should be placed on the class. See: MSDN

[Index(nameof(Url))]
public class Post
{
    public int PostId { get; set; }
    public string Url { get; set; }
    public string Title { get; set; }
    public DateTime PublishedOn { get; set; }
}

or revert to the fluent syntax for more advanced option:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasIndex(p => p.Url)
        .IncludeProperties(
            p => new { p.Title, p.PublishedOn });
}

EF 6.1

Since the release of EF 6.1. (March 17th, 2014) there is indeed an [Index] attribute available.

Functionality as:

[Index("IMEIIndex", IsUnique = true)]
public string IMEI { get; set; }

comes out of the box.

PS: other properties are Order and IsClustered.


According to this link: http://blogs.msdn.com/b/adonet/archive/2014/02/11/ef-6-1-0-beta-1-available.aspx

It will be available in EF 6.1 as a standard DataAnnotation attribute.

IndexAttribute allows indexes to be specified by placing an [Index] attribute on a property (or properties) in your Code First model. Code First will then create a corresponding index in the database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...