【问题标题】:How to share a connection string between multiple entity data model如何在多个实体数据模型之间共享连接字符串
【发布时间】:2012-04-22 09:47:32
【问题描述】:

我有一个包含 4 个实体数据模型的项目。为了构建它们,我不想在我的项目中保存连接字符串,我想将连接字符串存储在 app.config 文件中并在我的模型之间共享它。我如何可以吗?

谢谢

【问题讨论】:

  • 您可能必须通过代码传递连接字符串,这是有关它的详细答案forums.asp.net/t/1747809.aspx/1
  • 这个codefirst还是使用EDMX模型
  • @LukeMcGregor : 它是EDMX 模型
  • 我不是基于 EDMX 的 EF 的大专家,但从我刚刚尝试的结果来看,如果您在创建 edmx 模型时取消选中保存我的连接字符串位,它将使用已经存在的相同数据来源

标签: c# asp.net linq entity-framework c#-4.0


【解决方案1】:

首先假设 DbContext 和模型/数据库。

  1. 保持 app.config 文件中生成的 EF 连接字符串不变。正如 Arthur 所说,它们包含 EF 元数据 (csdl/ssdl/msl) 的路径。它们也被模型设计者在开发过程中使用。
  2. 添加一个名为 e.g. 的存储连接字符串“共享连接”。这是唯一需要在生产中修改的连接字符串。
  3. 创建一个派生自 DbContext 的基类,并从该类派生所有上下文。
  4. 在基类中显式创建默认 EF 连接。然后修改它以使用这样的共享连接字符串:
public class BaseContext : DbContext
{
    public BaseContext(string nameOrConnectionString)
        : base(CreateConnection(nameOrConnectionString), true)
    {
    }

    private static EntityConnection CreateConnection(string connectionString)
    {
        // Create a (plain old database) connection using the shared connection string.
        DbConnection dbConn = Database.DefaultConnectionFactory.CreateConnection(
            ConfigurationManager.ConnectionStrings["SharedConnection"].ConnectionString);

        // Create a helper EntityConnection object to build a MetadataWorkspace out of the
        // csdl/ssdl/msl parts of the generated EF connection string for this DbContext.
        EntityConnection wsBuilder = new EntityConnection(connectionString);

        // Merge the specific MetadataWorkspace and the shared DbConnection into a new EntityConnection.
        return new EntityConnection(wsBuilder.GetMetadataWorkspace(), dbConn);
    }
}

派生上下文的代码不会改变,只是它们必须从 BaseContext 继承。这是一个更健壮的 CreateConnection 方法。它具有错误处理功能,并以添加应用程序设置为代价从代码中删除共享连接字符串的名称。

private static EntityConnection CreateConnection(string connectionString)
{
    // Find the name of the shared connection string.
    const string appSettingKey = "SharedConnectionStringName";

    string sharedConnectionStringName = ConfigurationManager.AppSettings[appSettingKey];
    if (string.IsNullOrEmpty(sharedConnectionStringName))
    {
        throw new Exception(string.Format(
            "Shared connection not configured. " +
            "Please add a setting called \"{0}\" to the \"appSettings\" " +
            "section of the configuration file.", appSettingKey));
    }

    // Create a (plain old database) connection using the shared connection string.
    ConnectionStringSettings backendSettings =
        ConfigurationManager.ConnectionStrings[sharedConnectionStringName];
    if (backendSettings == null)
    {
        throw new Exception(string.Format(
            "Invalid connection string name \"{0}\" in appSetting \"{1}\"",
            sharedConnectionStringName, appSettingKey));
    }

    System.Data.Common.DbConnection dbConn =
        Database.DefaultConnectionFactory.CreateConnection(
        backendSettings.ConnectionString);

    // Create a helper EntityConnection object to build a MetadataWorkspace out of the
    // csdl/ssdl/msl parts of the generated EF connection string for this DbContext.
    EntityConnection wsBuilder = new EntityConnection(connectionString);

    // Merge the specific MetadataWorkspace and the shared DbConnection into a new EntityConnection.
    return new EntityConnection(wsBuilder.GetMetadataWorkspace(), dbConn);
}

【讨论】:

    【解决方案2】:

    您可以使用代码优先。您必须在代码中为每个模型编写映射,但是使用相同的连接字符串非常容易——只需将 "name=MyConnectionStringName" 传递给 DbContext 构造函数。

    当使用带有 EDMX 的 Database First 时,EF 连接字符串包含以下两者:

    • “存储连接字符串”提供有关如何连接到数据库的信息
    • 描述模型的 EF 元数据的路径

    由于每个模型的第二部分都不同,因此您需要有四个不同的连接字符串。

    如果您只想拥有一个连接字符串,那么您需要: - 以其他方式存储元数据信息 - 编写代码以加载元数据并创建 MetadataWorkspace - 读取您的单一商店连接字符串并从中创建连接 - 使用连接和 MetadataWorkspace 创建 EntityConnection - 使用 EntityConnection 创建一个 ObjectContext - 如果您使用 DbContext,则使用 ObjectContext 创建 DbContext

    似乎很难相信编写所有这些重要的代码会比在 app.config 中仅包含四个连接字符串更好。

    【讨论】:

    • 考虑以下场景 *您正在为一个数据库编写代码 *您在测试数据库上工作,因此您需要在生产环境中更改连接字符串
    【解决方案3】:

    您可以将 EF 连接字符串传递给 ObjectContext。如果您有多个模型,您可以将每个模型的连接字符串放在 app.config 中,给每个模型一个键,并在需要时查找它,并在实例化时将适当的字符串传递给上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-17
      • 2023-03-16
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多