为了获得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"
}
}