Identity (on database creation) error specified key was too long

╄→гoц情女王★ 提交于 2019-12-04 15:41:20

This problem is caused by UTF-8 columns that are too long and are being used as indexes. The best way to solve this would be to use a different database engine, but that is probably not the thing you want to hear. The second choice is to update the database schema to lower the limit of characters in the indexed fields.

http://wildlyinaccurate.com/mysql-specified-key-was-too-long-max-key-length-is-767-bytes

EDIT: The error is doscussed here: http://bugs.mysql.com/bug.php?id=70940 . The last post seems to offer a viable slution.

Through checking the SQL queries generated by EF, I had found that the problem was related to UserName (varchar utf8 256) in table AspNetUsers and Name (varchar utf8 256) in table AspNetRoles, while the table for HistoryRow was fine.

So the following codes resolved the problem.

    public class WebPortalDbContext : IdentityDbContext<ApplicationUser>
{
    public WebPortalDbContext()
        : base("IdentityConnection")
    {

    }

    public static WebPortalDbContext Create()
    {
        return new WebPortalDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>()
            .Property(c => c.Name).HasMaxLength(128).IsRequired();

        modelBuilder.Entity<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>().ToTable("AspNetUsers")//I have to declare the table name, otherwise IdentityUser will be created
            .Property(c => c.UserName).HasMaxLength(128).IsRequired();
    }


}

To clarify the solution, here's the libraries I am using:

  1. EF 6.1.0
  2. Microsoft ASP.NET Identity EntityFramework 2.0.0
  3. ASP.NET Identity Owin 2.0.0
  4. MySql .NET libraries 6.8.3

And this solution also works for

  1. EF 6.1.1
  2. Microsoft ASP.NET Identity EntityFramework 2.0.1
  3. ASP.NET Identity Owin 2.0.1

Just a shot in the dark ... I think the column that's being created for Application.UserName is too large for a unique index. See if you can influence the size of it by overriding the default:

public class ApplicationUser : IdentityUser
{
  [StringLength(200)]
  public override string UserName { get; set; }   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!