为了获得ASP.NET Core MVC网站,在崩溃后,我再次按照this thread的指示进行操作.

我安装了Visual Studio扩展,插入了四个Entity Framework Core引用,在用正确的值替换DbContext的名称之后,我根据this thread输入了dotnet ef database update等等.

我读了答案,当有错误时,白色背景.

(为了验证此步骤是否正确执行,我需要在解决方案中搜索什么内容?)

现在,我在下面的内容中处理"无法解决dbContext上的服务"错误,考虑到我所做的不同try 的次数,在我能够编写简明综合之前,有人可以更准确地指出这个错误似乎会有所帮助.在那之后,我将负责将连接字符串存储在一个更机密的地方,但首先获取网页上的数据可能是一个有趣的步骤.

如您所知,我可以创建一个订单控制器,但是当我试图显示它的索引页面时,我得到了错误

"InvalidOperationException:try 激活‘MVCumul_01.Controllers.OrdersController’时,无法解析类型为‘MVCumul_01.Models.NorthwinContext’的服务. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(Type类型,必填类型By)

我验证了连接字符串(该错误出现在上一次try 中).在Windows11版本23H2(OS Build 22631.3296)上,数据正确显示在Visual Studio2022社区中的服务器资源管理器中,和/或SSMS 19.1中

我首先忘记了在ConfigureServices中声明AddDbContextFactory,然后声明它和NorthwindContext都是singleton,然后都是作用域(这应该都有效),然后混合(这不应该工作,或者可能我混淆了,但不是...浪费旅行).

下面是代码:

Startup.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()
        {
        }
    }
}

Program.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();

ApplicationDbContextFactory.cs:

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);
        }
    }
}

appsettings.json:

{
    "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"
    }
}

推荐答案

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

它做到了,也没有做到.EF Core在默认的最小托管模式(模板使用的模式,即var builder = WebApplication.CreateBuilder(args);)下工作得很好.

go 掉Startup(它并没有被你的应用程序实际使用,所以它没有注册上下文)和CreateHostBuilder方法,并向builder.Services注册上下文,这样你的应用程序就可以实际使用它:

// ideally read connection string from the config
// builder.Configuration.GetConnectionString("DefaultConnection")
builder.Services
   .AddDbContextFactory<NorthwindContext>(options => options.UseSqlServer(...)); 

一般情况下,请不要将数据库上下文注册为单例,这会引起很多问题.

另见:

Csharp相关问答推荐

.NET框架4.7.2项目如何引用.NET Core 2.2库?

什么是通过反射创建类的泛型接口方法的正确方法?

如何使用CsvReader获取给定列索引的列标题?

Azure Function应用(. NET 8)不将信息记录到应用洞察

AsNoTrackingWithIdentitySolutions()似乎不起作用?

在命名管道上使用GRPC ASP.NET核心时如何配置命名管道权限

自定义列表按字符串的部分排序

交替的奇数

在C#ASP.NET内核中使用INT AS-1进行控制器场景的单元测试

如何让游戏对象在切换场景时被销毁,但在开始新游戏时重新锁定

ReadOnlyMemory访问基础索引的替代方案

如何正确处置所有动态控件?

多个参数的最小API删除

Autofac -动态实例化:手动传递构造函数

在.Net 8 Visual Studio 2022中启用本机AOT发布时发布失败

.NET8支持Vector512,但为什么向量不能达到512位?

使用生产环境调试我的应用程序的快速方法

在Swagger中显示自定义属性的属性名称

将两个JSON文件与覆盖值的主文件合并

Avalonia MVVM数据模板