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

EF Core Code First模式下添加Migrations失败求助(C#)

问题:EF Core Code First迁移报错“Unable to create an object of type 'MyAppContext'”

项目背景

正在构建一个包含简单CRUD操作的ASP.NET Web API项目,计划通过EF Core Code First模式结合Migrations生成数据库。项目结构为:ASP.NET Web API作为主项目,数据库上下文放在独立类库中。

类库代码

数据库上下文

using Microsoft.EntityFrameworkCore;
using MyApp.Database.Models;
namespace MyApp.Database.Context;
public class MyAppContext : DbContext
{
    public MyAppContext(DbContextOptions<MyAppContext> options) : base(options) { }
    public virtual DbSet<Booking> Bookings { get; set; }
    public virtual DbSet<Person> Persons { get; set; }

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

数据库模型

Booking类

namespace MyApp.Database.Models;
public class Booking
{
    public int Id { get; set; }
    public int Week { get; set; }
    public int DayOfWeek { get; set; }
    public int Hour { get; set; }
    public int PersonId { get; set; }
    public virtual Person Person { get; set; }
}

Person类

using System.Collections.Generic;
namespace MyApp.Database.Models;
public class Person
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public int Age { get; set; }
    public virtual IEnumerable<Booking> Bookings { get; set; }
}

数据初始化扩展类

using Microsoft.EntityFrameworkCore;
using MyApp.Database.Models;
namespace MyApp.Database;
public static class SeedExtension
{
    public static void Seed(this ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().HasData(new Person
        {
            Id = 1,
            Firstname = "John",
            Lastname = "Doe",
            Age = 28,
        });
    }
}

Web API项目配置

Program.cs中注册上下文:

builder.Services.AddDbContext<MyAppContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("MyAppDb"));
});

连接字符串(Web API项目的appsettings.json):

{
  "ConnectionStrings": {
    "MyAppDb": "server=(LocalDB)\\mssqllocaldb;database=MyAppDB;integrated security=True"
  }
}

当前问题

在Package Manager Console切换到类库项目,执行dotnet ef migrations add "Init"时,报错:Unable to create an object of type 'MyAppContext'。

项目环境:.NET 6,类库安装的NuGet包版本:

  • Microsoft.EntityFrameworkCore(7.0.2)
  • Microsoft.EntityFrameworkCore.SqlServer(7.0.2)
  • Microsoft.EntityFrameworkCore.Tools(7.0.2)

解决方案

核心原因

EF Core迁移工具在类库项目中运行时,无法获取Web API项目的配置信息(如连接字符串),也找不到上下文的实例化逻辑——类库没有Program.cs这类入口点提供服务注册。

解决步骤

  1. 指定启动项目执行迁移
    在Package Manager Console中执行命令时,明确指定Web API项目作为启动项目(它包含完整的配置和服务注册):

    dotnet ef migrations add Init --startup-project ../你的WebAPI项目相对路径
    

    或者在Package Manager Console的「默认项目」选择类库,「启动项目」选择Web API项目,直接执行:

    Add-Migration Init
    
  2. 添加设计时上下文工厂(更可靠的方案)
    在类库项目中新增一个设计时工厂类,让EF Core工具能直接创建上下文实例:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Design;
    using Microsoft.Extensions.Configuration;
    using System.IO;
    
    namespace MyApp.Database.Context;
    public class MyAppContextFactory : IDesignTimeDbContextFactory<MyAppContext>
    {
        public MyAppContext CreateDbContext(string[] args)
        {
            // 加载Web API项目的配置文件
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../你的WebAPI项目名称"))
                .AddJsonFile("appsettings.json")
                .Build();
    
            var optionsBuilder = new DbContextOptionsBuilder<MyAppContext>();
            optionsBuilder.UseSqlServer(configuration.GetConnectionString("MyAppDb"));
    
            return new MyAppContext(optionsBuilder.Options);
        }
    }
    

    替换代码中的../你的WebAPI项目名称为实际路径,添加后直接在类库项目下执行迁移命令即可,无需额外指定启动项目。

  3. 版本兼容优化
    当前项目用.NET 6,但EF Core用了7.0.2版本,虽能兼容,但建议统一版本:要么将EF Core降级到6.x系列,要么将Web API项目升级到.NET 7,避免潜在的版本冲突问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:01:29