You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:25:17