.Net 8添加EF迁移报错:无法创建CoffeeShopContext实例
报错信息
Unable to create a 'DbContext' of type 'CoffeeShopContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[DataLayer.Data.ContextManager.CoffeeShopContext]' while attempting to activate 'DataLayer.Data.ContextManager.CoffeeShopContext'.' was thrown while attempting to create an instance.
相关代码
Program.cs
using CoffeeShopAPI.DbIntializer; using CoffeeShopAPI.ServiceManager; using DataLayer.Data.ContextManager; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext<CoffeeShopContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddApplicationServices(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.MapControllers(); using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<CoffeeShopContext>(); db.Database.Migrate(); DbInitializer.Initialize(db); } app.Run();
Database Context(位于DataLayer > Data > ContextManager类库)
public class CoffeeShopContext: DbContext { public CoffeeShopContext(DbContextOptions<CoffeeShopContext> options) : base(options) { } public DbSet<CoffeeShop> CoffeeShops { get; set; } }
解决方案
指定启动项目执行迁移命令:由于DbContext在单独类库中,EF Core设计时无法自动识别Web项目的服务配置,执行迁移时需明确指定启动项目。示例命令:
dotnet ef migrations add InitialCreate --project DataLayer --startup-project CoffeeShopAPI其中
--project指定DbContext所在的类库项目,--startup-project指定包含Program.cs的Web API项目。实现IDesignTimeDbContextFactory:在DataLayer类库中添加一个实现
IDesignTimeDbContextFactory<CoffeeShopContext>的类,让EF Core在设计时能直接创建DbContext实例:using DataLayer.Data.ContextManager; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using System.IO; public class CoffeeShopContextFactory : IDesignTimeDbContextFactory<CoffeeShopContext> { public CoffeeShopContext CreateDbContext(string[] args) { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("../CoffeeShopAPI/appsettings.json") // 指向Web项目的配置文件路径 .Build(); var optionsBuilder = new DbContextOptionsBuilder<CoffeeShopContext>(); optionsBuilder.UseSqlite(configuration.GetConnectionString("DefaultConnection")); return new CoffeeShopContext(optionsBuilder.Options); } }注意根据项目实际结构调整appsettings.json的路径,确保设计时能读取到连接字符串。
检查连接字符串配置:确认Web项目的appsettings.json中存在格式正确的
DefaultConnection:{ "ConnectionStrings": { "DefaultConnection": "Data Source=CoffeeShop.db" } }
内容的提问来源于stack exchange,提问作者Kamran Khan

