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

Visual Studio 2022中EF Core迁移报错:无法解析IMigrator服务

问题描述
  • 首次提问,不清楚当前使用的.NET版本,需要查询方法。
  • 使用Visual Studio 2022,执行迁移命令时弹出以下错误:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Migrations.IMigrator'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

  • 执行的命令:add-migration -Name inicial

上下文代码

using cinepolis.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace cinepolis.DataBase
{
    public class CinepolisContext : IdentityDbContext<IdentityUser>
    {
        //constructor donde establecemos opciones
        public CinepolisContext(DbContextOptions options) : base(options)
        {
        }

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

        //Entidades que va a manejar
        public DbSet<Usuario> Usuarios { get; set; }
        public DbSet<Cliente> Clientes { get; set; }
        public DbSet<Empleado> Empleados { get; set; }
        public DbSet<Reserva> Reservas { get; set; }
        public DbSet<Sala> Salas { get; set; }
        public DbSet<Funcion> Funciones { get; set; }
        public DbSet<Pelicula> Peliculas { get; set; }
    }
}

appsettings.json配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "CinepolisDBCS": "server=(localdb)\\MSSQLLocalDB;database=CinepolisDB;Trusted_Connection=true;"
  }
}

启动文件代码

using cinepolis.DataBase;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

namespace cinepolis
{
    public static class Startup
    {
        public static WebApplication InicializarApp(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            ConfigureServices(builder);

            var app = builder.Build();
            Configure(app);

            return app;
        }

        private static void ConfigureServices(WebApplicationBuilder builder)
        {

            builder.Services.AddDbContext<CinepolisContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("CinepolisDBCS")));
            
            builder.Services.AddControllersWithViews();

        }

        public static void Configure(WebApplication app)
        {
            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        }
    }
}
解决方案

一、查询.NET版本的方法

  • 方法1:通过Visual Studio:右键项目 → 属性 → 应用程序 → 目标框架,即可看到当前使用的.NET版本。
  • 方法2:通过终端:打开项目目录下的终端(或Package Manager Console),执行命令 dotnet --version,即可查看当前SDK版本。

二、解决迁移错误的步骤

  1. 修正DbContext构造函数
    你的CinepolisContext构造函数使用了非泛型的DbContextOptions,这会导致依赖注入无法正确解析服务。需要修改为泛型版本:

    public CinepolisContext(DbContextOptions<CinepolisContext> options) : base(options)
    {
    }
    
  2. 检查NuGet包是否齐全
    确保已安装以下必要包:

    • Microsoft.EntityFrameworkCore.SqlServer:SQL Server数据库提供程序
    • Microsoft.EntityFrameworkCore.Tools:EF Core迁移工具
    • Microsoft.AspNetCore.Identity.EntityFrameworkCore:Identity与EF Core集成包
  3. 确保迁移命令执行环境正确

    • 如果使用Package Manager Console:确保“默认项目”选择了包含CinepolisContext的项目,启动项目也已正确设置。
    • 如果使用.NET CLI:在项目根目录执行命令:
      dotnet ef migrations add inicial --project cinepolis.DataBase --startup-project cinepolis
      
      (注意替换成你实际的项目名称)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:35:11