身份(在数据库创建时)错误指定密钥太长

我在这里有AspNet Identity和MySql的问题,问题是错误,它真的阻止了我,这个错误如下:

指定密钥太长,最大密钥长度为767字节

现在我按照使用MySql和Identity的教程:

http://www.asp.net/mvc/tutorials/security/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider

我想说我有进展,因为现在至少我得到了一些在MySQL中生成的表,但是我在这个问题上堆栈,很长一段时间我都试图解决这个问题,但没有成功。

我得到的错误在这部分:

public void InitializeDatabase(ApplicationDbContext context) { if (!context.Database.Exists()) { // if database did not exist before - create it context.Database.Create(); } else { // query to check if MigrationHistory table is present in the database var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery( string.Format( "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'", "Server=127.0.0.1;Database=mydb;uid=root;pwd=mypass;port=3351;")); // if MigrationHistory table is not there (which is the case first time we run) - create it if (migrationHistoryTableExists.FirstOrDefault() == 0) { context.Database.Delete(); context.Database.Create(); //<<<< i get here error } } } 

所以这会引发错误: context.Database.Create();

我试图调查究竟是什么问题,但我找不到:(

我尝试比较sql server生成的数据库中的数据并将相同的信息放在migrationtable中,通常我可以在workbench中的insert语句中放入相同的值。

也许有人可以帮我解决这个问题?

只是要注意,最后创建了所有表,但没有插入任何表,因为错误:/

以下是在mysql架构中创建的所有表: mysql列

我有一个小更新:它似乎尝试从2列migrationId和contextkey组合PK,这就是为什么你会遇到这种错误。

我可以在我的工作台中重现它,我试图改变表,通过将这些列设置为PK,我得到完全相同的错误。 但是,我怎么说只应该设置1个PK呢?

此问题是由UTF-8列引起的,这些列太长并且正在用作索引。 解决这个问题的最好方法是使用不同的数据库引擎,但这可能不是你想要听到的。 第二种选择是更新数据库模式以降低索引字段中的字符限制。

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

编辑:错误在这里doscussed: http ://bugs.mysql.com/bug.php?id = 70740。 最后一篇文章似乎提供了可行的洗脱。

通过检查EF生成的SQL查询,我发现该问题与表AspNetRoles中的表AspNetUsers和Name(varchar utf8 256)中的UserName(varchar utf8 256)有关,而HistoryRow的表很好。

所以以下代码解决了这个问题。

  public class WebPortalDbContext : IdentityDbContext { public WebPortalDbContext() : base("IdentityConnection") { } public static WebPortalDbContext Create() { return new WebPortalDbContext(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .Property(c => c.Name).HasMaxLength(128).IsRequired(); modelBuilder.Entity().ToTable("AspNetUsers")//I have to declare the table name, otherwise IdentityUser will be created .Property(c => c.UserName).HasMaxLength(128).IsRequired(); } } 

为了澄清解决方案,这里是我使用的库:

  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库6.8.3

而这个解决方案也适用于

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

只是在黑暗中拍摄…我认为为Application.UserName创建的列对于唯一索引来说太大了。 通过覆盖默认值来查看是否可以影响它的大小:

 public class ApplicationUser : IdentityUser { [StringLength(200)] public override string UserName { get; set; } }