实体框架核心1.0连接字符串 [英] Entity Framework Core 1.0 Connection Strings

查看:84
本文介绍了实体框架核心1.0连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发各种大型ASP.NET Core MVC 1.0应用程序.每个应用程序都有4层,如下所示:

We are working on a vary large ASP.NET Core MVC 1.0 application. We have 4-tiers to each of our applications as follows:

  1. DTO
  2. 存储库(实体框架-代码优先)
  3. 服务(业务逻辑)
  4. MVC(UI-MVC)

当前,在处理所有数据库操作的存储库中,我们已经在DbContext中对数据库连接字符串进行了硬编码,如下所示:

Currently, in our repositories, which handle all database operations we have hard coded the database connection strings in the DbContext as follows:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {

    optionsBuilder.UseSqlServer("Data Source=somedatabase.database.windows.net;Initial Catalog=database;Integrated Security=False;User ID=username;Password=password;Connect Timeout=60;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true");

}

此项目作为独立的ASP.NET Core 1.0项目在MVC项目之外.它还有一个空的Program.cs文件,似乎需要执行该命令才能执行代码到数据库的命令行(dotnet ef迁移添加和dotnet ef数据库更新).

This project is outside the MVC project as a standalone ASP.NET Core 1.0 project. It also has a empty Program.cs file in it which seems to be required to execute the code-to-database command lines (dotnet ef migrations add and dotnet ef database update).

在DbConext中具有硬编码的连接字符串的原因是,当我们使用以下代码时,执行dotnet ef命令时,我们得到的对象引用未设置为对象异常的实例.

The reason we have a hard coded connection string in the DbConext is because when we use the following code, we get an object reference not set to an instance to an object exception, when executing the dotnet ef commands.

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {

    optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["StandardDatabase"].ConnectionString);

  }

但是,由于我们有一个Program.cs,因此,如果我们为连接字符串添加Debug.WriteLine并运行项目,它将返回正确的连接字符串,并且如果我们在以下位置的appsettings.json文件中设置了连接字符串UI,UI也将成功连接.

However, since we have a Program.cs, if we add a Debug.WriteLine for the connection string and run the project, it does return the correct connections string and if we set the connection string in the appsettings.json file in the UI, the UI will successfully connect as well.

问题: 上面提到的堆栈是我们用于多个微型应用程序"的堆栈,这意味着我们有多个连接到多个数据库的项目.我们还想利用开发,登台和生产连接字符串.

THE ISSUE: The above mentioned stack is what we use for several "Micro Apps", which means we have several projects that connect to several databases. We also want to take advantage of Development, Staging and Production connection strings.

如果我们使用配置管理器连接字符串,那么一切对于日常操作都非常有用;但是,当我们想将Entity Frameworks代码用于数据库命令行时,我们需要进入要更新的每个存储库,并将DbContext更改为硬编码的连接字符串,执行命令,然后将其更改回完成时,这很麻烦.

If we use Configuration Manager Connection String, everything is good for daily operations; however, when ever we want to utilize Entity Frameworks code to database command lines, we need to go in to each repository we want to update and change the DbContext to a hard coded connection string, execute the commands, then change them back to when done, which becomes quite troublesome.

问题: 我们只是做错了吗?是否存在用于设置Entity Framework Core 1.0堆栈的最佳实践,该堆栈使我们不必手动更改DbContext但可以全面利用配置文件?

THE QUESTION: Are we just doing this wrong, is there a preferred practice for setting up an Entity Framework Core 1.0 stack which allows us not to manually have to change the DbContext but take advantage of configuration files across the board?

任何方向将不胜感激!

推荐答案

EF Core旨在通过依赖项注入进行配置.依赖注入使您的DbContext保持干净,并且独立于环境的实现细节.

EF Core is intended to be configured via dependency injection. Dependency injection keeps your DbContext clean, and independent of implementation details of the environment.

您最初对连接字符串进行硬编码的解决方案将DbContext与数据库位置的知识紧密结合在一起.显然这是一个问题.但是,您提出的解决方案将DbContext与特定配置文件的知识紧密结合在一起.这也是一个问题.

Your initial solution of hard-coding connection strings tightly coupled the DbContext to the knowledge of where the database is located. That's obviously a problem. But your proposed solution tightly couples the DbContext to the knowledge of a particular configuration file. That, too, is a problem.

要使DbContext与环境细节无关,请创建一个带有DbContextOptions参数并调用基类构造函数的构造函数.

To keep the DbContext independent of environmental details, create a constructor that takes a DbContextOptions parameter and calls the base class constructor.

public class MyContext : DbContext
{
    public MyContext(DbContextOptions options) :
        base(options)
    {
    }
}

执行此操作,而不是覆盖OnConfiguring.然后在主机应用程序的Startup.cs中对其进行初始化.这就是配置文件的知识所在的地方.

Do this instead of overriding OnConfiguring. Then initialize it in the Startup.cs of your host application. That's where the knowledge of the configuration file belongs.

public class Startup
{
    private IConfigurationRoot _configuration;

    public Startup(IHostingEnvironment env)
    {
        _configuration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json")
            .Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfigurationRoot>(_configuration);

        services.AddDbContext<MyContext>(options => options
            .UseSqlServer(_configuration.GetConnectionString("MyContext")));
    }
}

现在,您可以在任何地方使用DbContext.

Now you can use your DbContext from anywhere.

这篇关于实体框架核心1.0连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆