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

ASP.NET Core 5使用Identity+SQLite创建用户时遇序列匹配异常

问题解决:ASP.NET Core 5 Identity + SQLite 创建用户时的 TypeInitializationException 异常

异常原因

这个System.TypeInitializationException内部的Sequence contains more than one matching element错误,核心原因是EF Core相关NuGet包版本不匹配。ASP.NET Core 5要求所有EF Core、Identity相关包必须统一使用5.x系列版本,若混合了其他版本(比如6.x),会导致EF Core内部反射查询方法时出现重复匹配,触发该异常。另外,DbContext构造函数使用非泛型的DbContextOptions也可能引发配置问题,间接导致错误。

解决方案

1. 统一NuGet包版本

检查项目中以下包的版本,确保全部为5.x(与ASP.NET Core 5版本一致):

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Sqlite
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Tools(若使用迁移工具)

可通过NuGet包管理器更新,或直接修改.csproj文件中的版本号:

<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.17">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

2. 修正DbContext构造函数

将AppDBContext的构造函数改为使用泛型DbContextOptions<AppDBContext>,而非非泛型的DbContextOptions,确保配置正确绑定到当前上下文:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace DateApp.Db
{
    public class AppDBContext : IdentityDbContext
    {
        public AppDBContext(DbContextOptions<AppDBContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}

3. 验证服务配置

确保在Startup.cs(.NET 5使用Startup模式)中正确配置DbContext和Identity服务:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDBContext>(options =>
        options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<AppDBContext>();

    services.AddControllers();
    services.AddSwaggerGen();
}

同时在appsettings.json中配置正确的SQLite连接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=DateApp.db"
  }
}

4. 执行数据库迁移

确保Identity的表结构正确生成到SQLite数据库中:

  • 打开Package Manager Console,运行:
    Add-Migration InitialCreate
    Update-Database
    
  • 或使用.NET CLI命令:
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

验证修复

重新启动项目,通过Swagger调用POST /add接口,即可正常将用户写入SQLite数据库。

内容的提问来源于stack exchange,提问作者Majkelele

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:10:14