添加Identity脚手架项时触发代码生成器错误:length参数长度小于0
脚手架生成Identity时出现“长度小于零”错误的解决分析
问题场景
执行以下操作时触发错误:
- 在解决方案资源管理器中右键点击Areas文件夹
- 选择「添加」→「新建脚手架项」
- 选择Identity并点击「添加」
- 勾选“Override all files”选项
- 关联DbContext后点击添加
错误提示:
运行指定的代码生成器时出错:“长度小于零。”(参数“length”)
关联的Ecommerce DbContext代码
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Project.Areas.Products.Models.ProjectClasses; using System.Reflection.Emit; namespace Project.ECommerceDbContext { public class ECommerce : IdentityDbContext<IdentityUser> { public ECommerce(DbContextOptions<ECommerce> options) : base(options) { } public virtual DbSet<Product> Products { get; set; } public virtual DbSet<Category> Categories { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source=DESKTOP-KJE6SRJ;Initial Catalog=ECommerce;Integrated Security=True;Connect Timeout=30;Encrypt=True;Trust Server Certificate=True;Application Intent=ReadWrite;Multi Subnet Failover=False"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //继承自IdentityDbContext时触发错误 base.OnModelCreating(modelBuilder); new Product_Properties().Configure(modelBuilder.Entity<Product>()); new Category_Properties().Configure(modelBuilder.Entity<Category>()); } } }
排查与解决方向
- 检查实体配置类的字符串操作:“长度小于零”错误通常来自
Substring这类需要长度参数的方法,重点排查Product_Properties和Category_Properties的Configure方法,确认没有传入负数长度的情况。 - 移除硬编码连接字符串:将
OnConfiguring中的连接字符串移到appsettings.json,通过依赖注入配置DbContext,避免脚手架生成时解析连接字符串出错。 - 分步执行脚手架生成:先取消“Override all files”选项,仅生成基础Identity文件,确认无错误后再逐步覆盖需要自定义的文件。
- 排查Identity配置冲突:暂时注释
base.OnModelCreating(modelBuilder),执行脚手架生成测试,若错误消失则说明是Identity默认模型配置与自定义实体配置存在冲突,需要逐步合并配置。 - 确认DbContext的命名空间与类名:确保脚手架选择DbContext时,正确选中的是
Project.ECommerceDbContext.ECommerce类,而非命名空间。
内容的提问来源于stack exchange,提问作者S_ENG Osama
相关产品推荐
相关产品推荐

