EF操作AspNetRoleClaims失败但ADO.NET正常的问题求助
问题原因与解决方法
核心问题
你在Program.cs中配置Entity Framework Core DbContext时,错误地将连接字符串的名称直接传给了UseSqlServer方法,而非读取配置中对应的实际连接字符串内容:
// 错误写法:直接传字符串名称,EF会把它当成完整连接字符串解析 builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("DefaultConnectionString"));
Entity Framework Core无法将"DefaultConnectionString"解析为有效的SQL Server连接字符串,因此抛出System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.错误。
而你用ADO.NET时,正确通过_configuration.GetConnectionString("DefaultConnectionString")获取到了配置文件中定义的实际连接字符串,所以能正常运行。
解决步骤
修改Program.cs中的DbContext注册代码,通过builder.Configuration读取配置里的真实连接字符串:
// 正确写法:读取配置中对应的连接字符串值 builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectionString")));
额外检查项
确保你的ApplicationDbContext类中已正确声明对应DbSet,否则_context.AspNetRoleClaims会为null:
public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // 必须添加此DbSet才能让EF Core识别AspNetRoleClaims表 public DbSet<AspNetRoleClaim> AspNetRoleClaims { get; set; } }
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

