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

添加新表后Entity Framework Core无法创建迁移的问题

问题

我的DbContext中已有41张表,此前迁移操作均正常,但添加第42张表后,执行Add-Migration migrationName命令时出现错误,提示无法创建CommercatorContext实例,无法解析DbContextOptions<CommercatorContext>服务。我尝试将该表替换为仅包含主键和字符串属性的Test类,问题依旧;移除该表后,迁移操作恢复正常。是否存在表数量上限等未知限制?

错误日志

PM> Add-Migration promocode -verbose
Using project 'CommercatorCMS'.
Using startup project 'CommercatorCMS'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile H:\Dev\CommercatorCMS\bin\Debug\net6.0\CommercatorCMS.deps.json --additionalprobingpath C:\Users\DYLAN-PC\.nuget\packages --runtimeconfig H:\Dev\CommercatorCMS\bin\Debug\net6.0\CommercatorCMS.runtimeconfig.json C:\Users\DYLAN-PC\.nuget\packages\microsoft.entityframeworkcore.tools\6.0.8\tools\netcoreapp2.0\any\ef.dll migrations add promocode --json --verbose --no-color --prefix-output --assembly H:\Dev\CommercatorCMS\bin\Debug\net6.0\CommercatorCMS.dll --project H:\Dev\CommercatorCMS\CommercatorCMS.csproj --startup-assembly H:\Dev\CommercatorCMS\bin\Debug\net6.0\CommercatorCMS.dll --startup-project H:\Dev\CommercatorCMS\CommercatorCMS.csproj --project-dir H:\Dev\CommercatorCMS\ --language C# --configuration Debug --working-dir H:\Dev\CommercatorCMS --root-namespace CommercatorCMS --nullable
Using assembly 'CommercatorCMS'.
Using startup assembly 'CommercatorCMS'.
Using application base 'H:\Dev\CommercatorCMS\bin\Debug\net6.0'.
Using working directory 'H:\Dev\CommercatorCMS'.
Using root namespace 'CommercatorCMS'.
Using project directory 'H:\Dev\CommercatorCMS\'.
Remaining arguments: .
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'CommercatorCMS'...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Finding DbContext classes in the project...
Found DbContext 'CommercatorContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'CommercatorContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---&gt; System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[CommercatorCMS.Business.Data.CommercatorContext]' while attempting to activate 'CommercatorCMS.Business.Data.CommercatorContext'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.&lt;&gt;c__DisplayClass21_4.&lt;FindContextTypes&gt;b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.&lt;&gt;c__DisplayClass21_4.&lt;FindContextTypes&gt;b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.&lt;&gt;c__DisplayClass0_0.&lt;.ctor&gt;b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.&lt;&gt;c__DisplayClass3_0`1.&lt;Execute&gt;b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'CommercatorContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

DbContext代码

using CommercatorCMS.Models;
using Microsoft.EntityFrameworkCore;

namespace CommercatorCMS.Business.Data
{
    public class CommercatorContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Language> Languages { get; set; }
        public DbSet<Website> Websites { get; set; }
        public DbSet<WebsiteModule> WebsiteModules { get; set; }
        public DbSet<News> News { get; set; }
        public DbSet<Page> Pages { get; set; }
        public DbSet<PageTitle> PageTitles { get; set; }
        public DbSet<PageSection> PageSections { get; set; }
        public DbSet<PageSectionMedia> PageSectionMedias { get; set; }
        public DbSet<PageContent> PageContents { get; set; }
        public DbSet<Notification> Notifications { get; set; }
        public DbSet<UserNotification> UserNotifications { get; set; }
        public DbSet<Media> Medias { get; set; }
        public DbSet<ProductMedia> ProductMedia { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductDescription> ProductDescriptions { get; set; }
        public DbSet<ProductLabel> ProductLabels { get; set; }
        public DbSet<Stock> Stocks { get; set; }
        public DbSet<Roles> Roles { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderHistory> OrderHistories { get; set; }
        public DbSet<OrderState> OrderStates { get; set; }
        public DbSet<OrderContent> OrderContents { get; set; }
        public DbSet<Tickets> Tickets { get; set; }
        public DbSet<TicketProduct> TicketProducts { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Wishlist> Wishlist { get; set; }
        public DbSet<WishlistCustomer> WishlistCustomers { get; set; }
        public DbSet<WishlistProducts> WishlistProducts { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<CategoryLabel> CategoriesLabels { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<UserGroup> UserGroups { get; set; }
        public DbSet<Color> Colors { get; set; }
        public DbSet<Size> Sizes { get; set; }
        public DbSet<SizeLabel> SizeLabels { get; set; }
        public DbSet<ColorLabel> ColorLabels { get; set; }
        public DbSet<Birthlist> Birthlists { get; set; }
        public DbSet<BirthlistProduct> BirthlistProducts { get; set; }
        public DbSet<BirthlistCustomer> BirthlistCustomers { get; set; }
        public DbSet<Test> PromoCodes { get; set; } // ← Problem is HERE

        public CommercatorContext()
        {

        }

        public CommercatorContext(DbContextOptions<CommercatorContext> options) : base(options)
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
#if DEBUG
            optionsBuilder.UseSqlServer("Server=localhost\\MSSQLSERVER01;Database=CommercatorCMS;Trusted_Connection=True;"); //Local
#else
            optionsBuilder.UseSqlServer("Data Source=???.???.???.???,???,???;Initial Catalog=???????;Persist Security Info=False;User ID=???;Password=???;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"); //Prod
#endif
        }
    }
}

Test类代码

using System.ComponentModel.DataAnnotations;

namespace CommercatorCMS.Models
{
    public class Test
    {
        [Key]
        public Guid Id { get; set; }

        public string Message { get; set; }
    }
}

CSPROJ文件

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="Business\Tools\" />
    <Folder Include="Migrations\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="JsonWebToken" Version="1.9.3" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
  </ItemGroup>

  <ItemGroup>
    <Content Update="Views\WebPages\Index.cshtml">
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </Content>
  </ItemGroup>

</Project>
解决方案

EF Core不存在表数量上限的限制,这个错误本质是设计时DbContext实例化失败,和表数量无关,只是添加新表触发了这个潜在问题。以下是几种可行的解决方法:

1. 实现IDesignTimeDbContextFactory接口

在项目中添加一个实现类,让EF Core在设计时能直接创建DbContext实例,绕开依赖注入的问题:

using CommercatorCMS.Business.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace CommercatorCMS
{
    public class CommercatorContextFactory : IDesignTimeDbContextFactory<CommercatorContext>
    {
        public CommercatorContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<CommercatorContext>();
            optionsBuilder.UseSqlServer("Server=localhost\\MSSQLSERVER01;Database=CommercatorCMS;Trusted_Connection=True;");

            return new CommercatorContext(optionsBuilder.Options);
        }
    }
}

添加该类后,EF Core工具会优先使用它创建DbContext,无需依赖应用的DI容器。

2. 确保Program.cs中正确注册DbContext

检查你的Program.cs(.NET 6)是否正确配置了DbContext服务:

var builder = WebApplication.CreateBuilder(args);

// 注册DbContext服务
builder.Services.AddDbContext<CommercatorContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

同时在appsettings.json中添加对应的连接字符串配置:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost\\MSSQLSERVER01;Database=CommercatorCMS;Trusted_Connection=True;"
  }
}

这样设计时工具就能通过DI容器正确获取DbContextOptions。

3. 修改DbContext的无参构造函数

在DbContext的无参构造函数中直接配置选项,确保设计时能完成初始化:

public CommercatorContext()
{
    var optionsBuilder = new DbContextOptionsBuilder<CommercatorContext>();
    optionsBuilder.UseSqlServer("Server=localhost\\MSSQLSERVER01;Database=CommercatorCMS;Trusted_Connection=True;");
    this.Database.EnsureCreated();
}

该方式适合开发环境,生产环境建议仍通过DI注入配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:40:36