c# - 在 .NET 5 控制台应用程序中调用旧的 .NET Framework DbContext 类库应用程序?
问题描述
我正在 .NET Core 5 中编写一个简单的控制台应用程序,并且想使用现有的数据层和服务,这些都是用 .NET Framework 4.7 编写的。
到目前为止,我的方法是这样的:
class Program
{
private static IConfigurationRoot _configuration;
static void Main(string[] args)
{
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appsettings.json", false)
.Build();
var serviceProvider = new ServiceCollection()
.AddSingleton<IConfigurationRoot>(_configuration)
.AddSingleton<MyApp.DataLayer.Interfaces.IExample, MyApp.DataLayer.Concrete.Example>()
.AddSingleton<MyApp.Models.Interfaces.IExample2, MyApp.Models.Coordinators.Example2>()
.AddDbContext<DbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("MyConnectionString")))
.BuildServiceProvider();
var data = serviceProvider.GetService<IExample>().GetData();
// do a bunch of stuff here involving services passed into the ServiceCollection() call
}
appsettings.json
看起来像这样:
{
"ConnectionStrings":
{
"MyConnectionString": "Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI;"
}
}
我遇到的错误是:No connection string named 'MyConnectionString' could be found in the application config file.
到达数据层中的这段代码时会发生此错误: public MyAppContext() : base("name=MyConnectionString") {}
解决方案
您不能.AddDbContext
用于 EF6 DbContext,并且访问 .NET Framework 配置系统的 EF6 DbContext 无参数构造函数不起作用。
所以这:
.AddDbContext<MyContext>(options => options.UseSqlServer(_configuration.GetConnectionString("MyConnectionString")))
应该
.AddScoped<MyContext>(_ => new MyContext(_configuration.GetConnectionString("MyConnectionString")));
推荐阅读
- excel - 根据给定条件的第一个字符查找 MAX
- python - 在 pandas 数据框中迭代超过 7000 万行的最快方法
- angular - 我想取消选中使用拼接删除提交的复选框
- php - 错误 400:错误请求,您的浏览器发送了此服务器无法理解的请求
- java - Spring Webflux 流量
- > 到通量
- maven - 找不到 io.confluent:kafka-protobuf-serializer:6.0.0
- oracle-spatial - 两个多边形 SDO_OVERLAPS,但它们的交点是 LINESTRING
- python - 如何对堆积数据(python)上的趋势进行分类?
- flutter - 当 InteractiveViewer 放大时,可拖动的反馈小部件获得偏移
- android - Android显示通话屏幕(使用fullScreenIntent)无抬头状态