ASP.NET Core Web API添加数据库连接字符串触发访问冲突错误
问题分析与解决方案
核心问题:服务注册顺序错误
你当前的Program.cs中,在调用var app = builder.Build();之后才注册DbContext,这是致命错误。因为builder.Build()会完成服务容器的初始化并创建WebApplication实例,此时服务容器已被冻结,无法再添加新服务,强行添加会触发内存访问冲突(0xc0000005错误)。
修复步骤
1. 调整服务注册顺序
将AddDbContext的代码移到builder.Build()之前,所有服务注册必须在构建应用实例前完成。修改后的Program.cs如下:
using Microsoft.EntityFrameworkCore; using StudentAPI.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // 把DbContext注册移到这里,在builder.Build()之前 builder.Services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("WebApiContext"))); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
2. 补充DbContext中缺失的DbSet
你的DatabaseContext中配置了StudentCourses实体的关系,但没有声明对应的DbSet,这会导致EF Core模型构建异常。需要添加对应DbSet:
public DbSet<StudentCourses> StudentCourses { get; set; } = null!;
修改后的DatabaseContext相关部分:
public class DatabaseContext : DbContext { public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } public DbSet<Student> Students { get; set; } = null!; public DbSet<Team> Teams { get; set; } = null!; public DbSet<Courses> Courses { get; set; } = null!; // 添加这一行 public DbSet<StudentCourses> StudentCourses { get; set; } = null!; // 其余OnModelCreating代码不变... }
3. 验证NuGet包版本一致性
确保项目中Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.SqlServer和Microsoft.EntityFrameworkCore.Tools的版本完全一致,版本不匹配也可能导致奇怪的运行时错误。
4. 检查LocalDB可用性
确认你的机器上已安装LocalDB,并且连接字符串中的实例名称正确。可以打开命令提示符,输入sqllocaldb info查看已有的实例,确保mssqllocaldb存在。
额外建议
- 首次运行前,执行EF Core迁移命令创建数据库:
Add-Migration InitialCreate Update-Database - 开发环境下可以启用EF Core日志,方便排查模型或连接问题:
options.UseSqlServer(...) .LogTo(Console.WriteLine, LogLevel.Information);
内容的提问来源于stack exchange,提问作者Alexander Thomsen
相关产品推荐
相关产品推荐

