ASP.NET-Identity Limit UserName Length

How can I limit the UserName field in the AspNetUsers table?

Nothing:

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

or that:

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

work.

I need this because setting Index to nvarchar(max) gives me this msg error:

The column "UserName" in the table "dbo.AspNetUsers" has a type that is not valid for use as a key column in the index.

To be detailed, I tried to set the indexes as follows:

 public override void Up() { CreateIndex("dbo.AspNetUsers", "UserName", true, "IX_UserName"); } public override void Down() { DropIndex("dbo.AspNetUsers", "IX_UserName"); } 
+5
entity-framework username asp.net-identity ef-code-first entity-framework-6
source share
3 answers

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

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

+4
source share

try it

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

A lot of time has passed, but I think that someone can still find it useful. I had the same problem and found the key to my solution. Migration mechanisms ignore the MaxLength attribute, but fixes can be added 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 fields are shortened, and SQL queries on UserName are faster (at least with mySQL, which I use), because indexes are used for efficient searches.

0
source share

All Articles