无法解析 dbContext 的服务(抱歉那个经典标题)

问题描述 投票:0回答:1

为了获取 MVCCore 网站,在崩溃后,我再次按照此线程的指示进行操作。

我安装了 Visual Studio 扩展,插入了四个 EntityFrameworkCore 引用,在用正确的值替换 dbContext 的名称后,根据

这个线程
输入了 dotnet ef database update 等等。

我阅读了答案,如有任何错误,都会在白色背景上显示。

(有什么我必须在解决方案中搜索,以验证此步骤是否正确执行?)

现在,我正在处理下面的“无法解析 dbContext 上的服务”错误,并且考虑到我所做的不同尝试的次数,似乎有人可以在我之前更准确地指出该错误,这可能会有所帮助能够写出简洁的综合。之后,我将负责将连接字符串存储在更机密的位置,但首先获取网页上的数据可能是一个有趣的步骤。 如您所知,我可以创建一个订单控制器,但是当我尝试显示其索引页面时,我收到错误

“InvalidOperationException:无法解析类型的服务 尝试激活时出现“MVCcumul_01.Models.NorthwindContext” 'MVCcumul_01.Controllers.OrdersController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(类型 类型,需要类型)”

我验证了连接字符串(该错误出现在过去的尝试中)。在 Windows 11 版本 23H2(操作系统内部版本 22631.3296)上,Visual Studio 2022 Community 中的服务器资源管理器和/或 SSMS 19.1 中的数据可以正确显示

我首先忘记了在ConfigureServices中声明AddDbContextFactory,然后将它和NorthwindContext声明为Singleton,然后都声明为Scoped(应该都有效),然后混合(这不应该工作,或者也许我混淆了,但不是...浪费旅行)。

这是代码:

启动.cs


using Microsoft.EntityFrameworkCore;
using MVCcumul_01.Models;

namespace MVCcumul_01
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = @"Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Encrypt=True;TrustServer²Certificate=True";

            services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString),
                ServiceLifetime.Singleton);

            services.AddDbContextFactory<NorthwindContext>(
               options => options.UseSqlServer(),
                lifetime: ServiceLifetime.Singleton);
        }


        public void Configure()
        {
        }


    }
}

程序.cs

using Microsoft.EntityFrameworkCore;
using MVCcumul_01.Models;

namespace MVCcumul_01
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = @"Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Encrypt=True;TrustServer²Certificate=True";

            services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString),
                ServiceLifetime.Singleton);

            services.AddDbContextFactory<NorthwindContext>(
               options => options.UseSqlServer(),
                lifetime: ServiceLifetime.Singleton);
        }


        public void Configure()
        {
        }


    }
}

ApplicationDbContextFactory.cs


using Microsoft.AspNetCore.Hosting;
using MVCcumul_01;

// EF Core uses this method at design time to access the DbContext
static IHostBuilder CreateHostBuilder(string[] args)
    => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
            webBuilder => webBuilder.UseStartup<Startup>()); 


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

using Microsoft.AspNetCore.Hosting;
using MVCcumul_01;

// EF Core uses this method at design time to access the DbContext
static IHostBuilder CreateHostBuilder(string[] args)
    => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
            webBuilder => webBuilder.UseStartup<Startup>()); 


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

appsettings.json


using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;

namespace MVCcumul_01.Models
{
    internal class ApplicationDbContextFactory : IDesignTimeDbContextFactory<NorthwindContext>
    {
        NorthwindContext IDesignTimeDbContextFactory<NorthwindContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<NorthwindContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            builder.UseSqlServer(connectionString);

            return new NorthwindContext(builder.Options);
        }
    }
}

我对错误消息感到惊讶“您的帖子似乎包含未正确格式化为代码的代码。请使用代码工具栏按钮或 CTRL+K 键盘快捷键将所有代码缩进 4 个空格。如需更多编辑帮助,请单击[?] 工具栏图标。”

帮助工具指向的行缩进了 10 个空格。代码缩进是否不建议?

c# asp.net-mvc entity-framework
1个回答
0
投票

// EF Core 在设计时使用此方法来访问 DbContext

有也有没有。 EF Core 在默认的最小托管模型(模板使用的模型,即

using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;

namespace MVCcumul_01.Models
{
    internal class ApplicationDbContextFactory : IDesignTimeDbContextFactory<NorthwindContext>
    {
        NorthwindContext IDesignTimeDbContextFactory<NorthwindContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<NorthwindContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            builder.UseSqlServer(connectionString);

            return new NorthwindContext(builder.Options);
        }
    }
}
)下工作得很好。

删除


{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "MVCcumul_01Context1": "Server=(localdb)\\mssqllocaldb;Database=MVCcumul_01Context-bfca8e78-d989-4ba3-a265-435e16ece2bb;Trusted_Connection=True;MultipleActiveResultSets=true",
        "MVCcumul_01Context": "Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Encrypt=True;Trust Server Certificate=True"
    }
}
方法并使用
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "MVCcumul_01Context1": "Server=(localdb)\\mssqllocaldb;Database=MVCcumul_01Context-bfca8e78-d989-4ba3-a265-435e16ece2bb;Trusted_Connection=True;MultipleActiveResultSets=true",
        "MVCcumul_01Context": "Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Encrypt=True;Trust Server Certificate=True"
    }
}
注册上下文,以便您的应用程序可以实际使用它:

var builder = WebApplication.CreateBuilder(args);
© www.soinside.com 2019 - 2024. All rights reserved.