如何共享多个实体数据模型之间的连接字符串 [英] How to share a connection string between multiple entity data model

查看:107
本文介绍了如何共享多个实体数据模型之间的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了model.for构建他们,我不想保存在连接字符串中我的项目,我希望有一个连接字符串存储在的app.config 文件和我之间models.How分享,我可以做到这一点?



感谢


解决方案

假设的DbContext和模型/数据库第一。




  1. 将生成的EF连接在你的app.config文件中的字符串完整。正如亚瑟说,它们所包含的路径的EF元数据(CSDL / SSDL / MSL)。它们由模型设计开发过程中也可使用。

  2. 添加例如称为存储连接字符串SharedConnection。这是一个需要在生产中进行修改的唯一的连接字符串。
  3. 创建一个基类从派生的DbContext派生和从该类的所有上下文。

  4. 在基类中显式地创建默认EF连接。然后修改它使用共享连接字符串这样的:



 公共类BaseContext:的DbContext 
{
公共BaseContext(字符串nameOrConnectionString)
:基地(创建连接(nameOrConnectionString),真)
{
}

私有静态EntityConnection创建连接(字符串的connectionString)
{
//使用共享的连接字符串(普通的旧数据库)的连接。
的DbConnection dbConn = Database.DefaultConnectionFactory.CreateConnection(
ConfigurationManager.ConnectionStrings [SharedConnection]的ConnectionString);

//创建一个帮助EntityConnection对象建立一个MetadataWorkspace出
的// CSDL / SSDL /本的DbContext生成的EF连接字符串的MSL部分。
EntityConnection wsBuilder =新的EntityConnection(的connectionString);

//合并的具体MetadataWorkspace和共享的DbConnection到一个新的EntityConnection。
返回新的EntityConnection(wsBuilder.GetMetadataWorkspace(),dbConn);
}
}



派生上下文的代码不只是改变他们必须从BaseContext继承。这是一个更强大的创建连接的方法。它有错误处理,并删除在添加应用程序设置价格的代码共享连接字符串的名称。

 私人静态EntityConnection创建连接(字符串的connectionString)
{
//查找共享连接字符串的名称。
常量字符串appSettingKey =SharedConnectionStringName;

串sharedConnectionStringName = ConfigurationManager.AppSettings [appSettingKey]
如果未配置共享连接。(string.IsNullOrEmpty(sharedConnectionStringName))
{
抛出新的异常(的String.Format(
+
请添加设置称为\{0} \到\appSettings\+
配置文件的部分。,appSettingKey));
}

//使用共享的连接字符串(普通的旧数据库)的连接。
ConnectionStringSettings backendSettings =
ConfigurationManager.ConnectionStrings [sharedConnectionStringName]
如果(backendSettings == NULL)
{
抛出新的异常(的String.Format(
无效的连接字符串名称\{0} \在appSetting \ {1} \,
sharedConnectionStringName,appSettingKey));
}

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

//创建一个帮助EntityConnection对象建立一个MetadataWorkspace出
的// CSDL / SSDL /本的DbContext生成的EF连接字符串的MSL部分。
EntityConnection wsBuilder =新的EntityConnection(的connectionString);

//合并的具体MetadataWorkspace和共享的DbConnection到一个新的EntityConnection。
返回新的EntityConnection(wsBuilder.GetMetadataWorkspace(),dbConn);
}


I have a project that has 4 entity data model.for building them I don't want save a connection string in my project and I want store a connection string in app.config files and share it between my models.How I can do this?

thanks

解决方案

Assuming DbContext and model/database first.

  1. Leave the generated EF connection strings in your app.config file intact. As Arthur said, they contain the paths to the EF metadata (csdl/ssdl/msl). They are also used during development by the model designer.
  2. Add a store connection string called e.g. "SharedConnection". This is the only connection string which needs to be modified in production.
  3. Create a base class which derives from DbContext and derive all your contexts from that class.
  4. Create the default EF connection explicitely in the base class. Then modify it to use the shared connection string like that:

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);
    }
}

The code of the derived contexts does not change except that they must inherit from BaseContext. Here is a more robust CreateConnection method. It has error handling and removes the name of the shared connection string from the code at the price of adding an application setting.

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);
}

这篇关于如何共享多个实体数据模型之间的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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