Creating Unique Index with Entity Framework 6.1 fluent API

后端 未结 6 642
醉话见心
醉话见心 2020-12-08 18:49

I have a column \"Name\" that must be unqiue. No foreign key or anything like that.

EF 6.1 finally supports creating such indexes via Annotations. That has been disc

6条回答
  •  半阙折子戏
    2020-12-08 19:22

    For me, using MVC 5 and EF 6, the key point was specifying a length on the string property where I wanted to place the index.

    protected override void OnModelCreating(DbModelBuilder modelBuilder){
        //More stuff
        modelBuilder.Entity().Property(c => c.Name).HasColumnType("nvarchar").HasMaxLength(50);
        modelBuilder.Entity().HasIndex(c => c.Name).IsUnique(true); 
    }
    

提交回复
热议问题