ASP.NET-Identity limit UserName length

我的未来我决定 提交于 2019-12-05 03:09:21

In the latest version released today, this should do the trick:

modelBuilder.Entity<ApplicationUser>().Property(x => x.UserName).HasMaxLength(15);

Try this

public class ApplicationUser : IdentityUser
{
    [Required, MaxLength(15)]
    public override string UserName { get; set; }

}

A lot of time has passed, but I think someone may still find it useful. I've had the same problem and found a clue to my solution here. The migration mechanisms ignore the MaxLength attribute, but one can add the corrections manually:

public override void Up()
{
    AlterColumn("dbo.AspNetUsers", "UserName", c => c.String(nullable: false, maxLength: 15, storeType: "nvarchar"));
    CreateIndex("dbo.AspNetUsers", "UserName");
}

public override void Down()
{
    DropIndex("dbo.AspNetUsers", new[] { "UserName" });
    AlterColumn("dbo.AspNetUsers", "UserName", c => c.String(nullable: false, maxLength: 256, storeType: "nvarchar"));
}

After update-database the fields are shortened and the SQL queries searching by UserName run faster (at least with mySQL which I use), because the indexes are used to search efficiently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!