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

.Net 8添加EF迁移报错:无法创建CoffeeShopContext实例

EF Core添加迁移时无法创建DbContext实例

报错信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:32:40