使用EntityConnectionStringBuilder构建动态IdeaBlade连接字符串

时间:2015-09-27 14:09:43

标签: c# winforms entity-framework devforce

好而不是与xml战斗,我被引导到EntityConnectionStringBuilder。所以这就是我到目前为止所拥有的。 EnityManagerFactory调用Create方法。现在Create方法创建并返回EntityManager,在本例中称为UnionEntities

  public UnionEntities Create()
        {
            string providerName = "System.Data.SqlClient";
            string serverName = ConfigurationManager.AppSettings["DatabaseServer"];
            string databaseName = ConfigurationManager.AppSettings["DatabaseName"];
            string userName = ConfigurationManager.AppSettings["DatabaseUserName"];
            string password = ConfigurationManager.AppSettings["DatabasePassword"];
            bool integratedSecurity = bool.Parse(ConfigurationManager.AppSettings["IntegratedSecurity"]);

            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity = integratedSecurity;
            sqlBuilder.UserID = userName;
            sqlBuilder.Password = password;

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/UnionModel.csdl|
                        res://*/UnionModel.ssdl|
                        res://*/UnionModel.msl";

            var manager = new UnionEntities();
            manager.Saving += SaveValidationHelper.SavingHandler;
            manager.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;

            return manager;
        }

现在通常新的UnionEntities()使用ConnectionString中的app.Config file。我现在如何告诉它使用我的EntityConnectionStringBuilder对象?

1 个答案:

答案 0 :(得分:1)

您可以在DevForce中实现IDataSourceKeyResolver来动态构建或修改连接字符串。该链接将带您进入DevForce资源中心的一个主题,但如果您在那里搜索" IDataSourceKeyResolver"您将找到更多信息和样本。