Yustme
Yustme

Reputation: 6265

ASP.NET-Identity: how to limit UserName length?

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

Neither this:

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

}

or this:

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

works.

I need this because setting an Index on an nvarchar(max) gives me this error message:

Column 'UserName' in table 'dbo.AspNetUsers' is of a type that is invalid for use as a key column in an index.

To be verbose, I was trying to set the indexes like this:

public override void Up()
{
    CreateIndex("dbo.AspNetUsers", "UserName", true, "IX_UserName");
}
        
public override void Down()
{
    DropIndex("dbo.AspNetUsers", "IX_UserName");
}

Upvotes: 9

Views: 5547

Answers (3)

Krzysztof
Krzysztof

Reputation: 1

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.

Upvotes: 0

Yustme
Yustme

Reputation: 6265

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

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

Upvotes: 6

Suhas Joshi
Suhas Joshi

Reputation: 1060

Try this

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

}

Upvotes: -1

Related Questions