在 .NET 5 控制台应用程序中调用较旧的 .NET Framework DbContext class 库应用程序?

Calling older .NET Framework DbContext class library application within a .NET 5 console application?

我正在 .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") {}

查看这个使用 EF 6 in .NET Core 的示例。

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

所以这个:

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

应该是

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

扩展 DbContext 的 class 的构造函数将使用如下所示的构造函数:

public DbEntities(IConfiguration _configuration) :
    base(new DbContextOptionsBuilder<DbEntities>()
        .UseSqlServer(_configuration.GetValue<string>("ConnectionStrings:MyConnectionString"))
        .Options)
{ }

注意:如果您使用的是 Entity Framework 核心,您应该创建一个单独的 DbEntities 文件,其中将包含所有 Entity Framework 属性和方法。