【发布时间】:2021-03-29 18:04:58
【问题描述】:
我正在 .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") {}
【问题讨论】:
-
你在哪里定义
_connectionString? -
对不起,我的代码粘贴/简化不好。已编辑。
-
.NETt 5 是 .NET Core 5。它不能使用任何 .NET 旧库。该库应至少修改为面向 .NET Standard,并使用面向 .NET Core 或 .NET Standard 的 EF 版本,如 EF 6.4.4 或所有 EF Core 版本
-
如果您的 DbContext 是旧的 .Net 4.7,那么它希望您的连接字符串在 app.config 或 web.config 中,而不是在 appSettings.json 中
标签: c# .net entity-framework .net-5