首页 > 解决方案 > 在 .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") {}

标签: c#.netentity-framework.net-5

解决方案


查看在 .NET Core 中使用 EF 6 的示例。

您不能.AddDbContext用于 EF6 DbContext,并且访问 .NET Framework 配置系统的 EF6 DbContext 无参数构造函数不起作用。

所以这:

.AddDbContext<MyContext>(options => options.UseSqlServer(_configuration.GetConnectionString("MyConnectionString")))
      

应该

 .AddScoped<MyContext>(_ => new MyContext(_configuration.GetConnectionString("MyConnectionString")));

推荐阅读