当 Entity Framework 模型位于专用的 class 库中时,如何在 C# 应用程序中定义连接字符串和数据库提供程序?

How to define connection string and database provider in an C# application when the Entity Framework model is in a dedicated class library?

我正在创建一组桌面应用程序(C#、.NET Framework 4.7),它们都使用相同的数据库和模型。我正在使用 Entity Framework 6 来设置数据库模型。为了防止重复代码(模型),我将所有模型放在专用的 "database" class 中。在这个class中,我还定义了DbContext.

当通过 NuGet 添加 EntityFramework 包到 "database" class 时,SQLServer LocalDB 的 EF 数据库提供程序也会自动安装。

在没有进一步配置的情况下启动应用程序会导致 SQLServer LocalDB 初始化并用于数据库连接。

我对 "database endpoint" 配置有 2 个顾虑。

1) 我要在实际应用中设置数据库连接字符串。因此,可能 运行 在不同机器上的每个应用程序都可以有自己的数据库连接字符串以指向同一数据库服务器。

为此,我将 "database" class 中的当前 DbConext 修改为以下内容:

public class MyDbContext : DbContext
{
    public MyDbContext(string connectionString)
    {
        this.Database.Connection.ConnectionString = connectionString;
    }
}

现在我可以通过应用程序定义数据库连接字符串,而不是常见的 "database" class。

2) 我想在应用程序级别定义数据库引擎。这样我就可以将 "database" class 创建为 "generic class" 并定义实际的 EF 数据库提供程序也在应用程序中使用。

我如何修改我的公共 "database" class 和应用程序,让应用程序决定要使用哪个 EF 数据库提供程序?

假设您使用的是 Asp net Core。

这就是您的 startup.cs 的样子。

       public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc();

            services.AddDbContext<MyDbContext>(op => op.UseSqlServer(Configuration["DbConnection"]));
       }

这就是您的 DbContext 构造函数的样子。

public RipBookDbContext(DbContextOptions<RipBookDbContext> options) : base(options)
{

}

您的连接字符串将在 appSettings.json 中保存为

"DbConnection": "Data Source=.;Initial Catalog=DbName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"

在此之后,您可以将 DbContext class 注入任何您想要使用它的地方。

您可以为您的 DBContext 公开一个接口。然后使用工厂模式使用适当的提供者创建正确的上下文。微软在这里有一个很好的例子:

https://github.com/Microsoft/InventorySample/tree/master/src

EF 通过 app.config/web.config 使用 <connectionStrings> 部分支持开箱即用。

在您的应用程序 app.config 中,添加:

然后在你的 DbContext class:

public class MyDbContext : DbContext
{
    public MyDbContext() 
        : base("ApplicationDatabase")
    { }

    public MyDbContext(string connectionString) 
        : base(connectionString)
    { }
}

这样,每个客户端实例都可以在运行时自定义其连接字符串,方法是为 Windows 应用程序调整 MyApplication.exe.config 文件中的 "ApplicationDatabase" 连接字符串。如果未提供连接 string/setting,以上代码默认为 "ApplicationDatabase" 连接字符串,或者您可以使用给定的连接字符串或连接字符串设置构造一个。