当前位置: 代码迷 >> 综合 >> ASPNetCore 使用EF 为Identity 生成 Mysql 表时报错: Specified key was too long; max key length is 3072 bytes
  详细解决方案

ASPNetCore 使用EF 为Identity 生成 Mysql 表时报错: Specified key was too long; max key length is 3072 bytes

热度:24   发布时间:2023-12-14 21:20:11.0

出错的sql语句:

CREATE TABLE `AspNetUserTokens` (
    `UserId` varchar(767) NOT NULL,
    `LoginProvider` varchar(767) NOT NULL,
    `Name` varchar(767) NOT NULL,
    `Value` text NULL,
    PRIMARY KEY (`UserId`, `LoginProvider`, `Name`),
    CONSTRAINT `FK_AspNetUserTokens_AspNetUsers_UserId` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE RESTRICT
);

报错:

Specified key was too long; max key length is 3072 bytes

建立索引时,数据库计算key的长度是累加所有Index用到的字段的char长度后再按下面比例乘起来不能超过限定的key长度
latin1 = 1 byte = 1 character 
uft8 = 3 byte = 1 character 
gbk = 2 byte = 1 character 

如果Mysql数据库编码

用的是Utf8 3*767*3=6903>3072

用的是GBK 3*767*2=4602>3072

用的是Latin1 3*767*1=2301<3072

所以如果你把数据库的编码改成Latin1 上面的语句是可以通过的,但是你要用中文肯定不行

解决方法:

修改EF自动生成的语句

重载你的AppDbContext类中的OnModelCreateing方法

protected override void OnModelCreating(ModelBuilder builder)
{base.OnModelCreating(builder);builder.Entity<IdentityUser>(entity => entity.Property(m => m.Id).HasMaxLength(85));builder.Entity<IdentityUser>(entity => entity.Property(m => m.NormalizedEmail).HasMaxLength(85));builder.Entity<IdentityUser>(entity => entity.Property(m => m.NormalizedUserName).HasMaxLength(85));builder.Entity<IdentityRole>(entity => entity.Property(m => m.Id).HasMaxLength(85));builder.Entity<IdentityRole>(entity => entity.Property(m => m.NormalizedName).HasMaxLength(85));builder.Entity<IdentityUserLogin<string>>(entity => entity.Property(m => m.LoginProvider).HasMaxLength(85));builder.Entity<IdentityUserLogin<string>>(entity => entity.Property(m => m.ProviderKey).HasMaxLength(85));builder.Entity<IdentityUserLogin<string>>(entity => entity.Property(m => m.UserId).HasMaxLength(85));builder.Entity<IdentityUserRole<string>>(entity => entity.Property(m => m.UserId).HasMaxLength(85));builder.Entity<IdentityUserRole<string>>(entity => entity.Property(m => m.RoleId).HasMaxLength(85));builder.Entity<IdentityUserToken<string>>(entity => entity.Property(m => m.UserId).HasMaxLength(85));builder.Entity<IdentityUserToken<string>>(entity => entity.Property(m => m.LoginProvider).HasMaxLength(85));builder.Entity<IdentityUserToken<string>>(entity => entity.Property(m => m.Name).HasMaxLength(85));builder.Entity<IdentityUserClaim<string>>(entity => entity.Property(m => m.Id).HasMaxLength(85));builder.Entity<IdentityUserClaim<string>>(entity => entity.Property(m => m.UserId).HasMaxLength(85));builder.Entity<IdentityRoleClaim<string>>(entity => entity.Property(m => m.Id).HasMaxLength(85));builder.Entity<IdentityRoleClaim<string>>(entity => entity.Property(m => m.RoleId).HasMaxLength(85));
}

参考链接

https://my.oschina.net/airship/blog/1587577

https://retifrav.github.io/blog/2018/03/20/csharp-dotnet-core-identity-mysql/

 

 

  相关解决方案