【问题标题】:Calling older .NET Framework DbContext class library application within a .NET 5 console application?在 .NET 5 控制台应用程序中调用旧的 .NET Framework DbContext 类库应用程序?
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    查看这个使用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")));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2020-04-14
      • 2012-01-16
      • 1970-01-01
      相关资源
      最近更新 更多