从应用程序配置文件中获取EntityConnection字符串

时间:2012-11-29 00:12:20

标签: c# .net sql-server entity-framework connection-string

一些简单的问题:

所以我有这个LogInWindow对话框用于收集所有SQL登录信息,然后将构造的连接字符串传递给ServiceManager.InitializeContext()方法,该方法使用特定的提供者连接初始化我的实体上下文。

一切正常。但我想使用App.config配置文件中定义的值初始化LogInWindow对话框。

是否有首选方法进行此初始设置?即,我是否应该使用默认构造函数来实例化一个虚拟EntityContext,仅仅是出于获取默认提供者连接的纯粹目的?是否有“更清洁”的方式?

顺便说一下,你会认为在Form.Close()事件的处理程序中进行这种类型的Form.Shown调用是一种“安全”的做法吗?我在MSDN上读到,不建议在Form.Close()事件的处理程序中调用Form.Load

public partial class MainWindow : Form {

    private void MainWindow_Shown(object sender, EventArgs e) {
        using (var logInWindow = new LogInWindow()) {
            if (logInWindow.ShowDialog(this) == DialogResult.OK) {
                this.serviceManager.InitializeContext(logInWindow.ConnectionString);
            } else {
                this.Close();
            }
        }
    }
}


public sealed class ServiceManager : IDisposable {

    public void InitializeContext(string connectionString) {
        if (this.EntityContext != null)
            throw new InvalidOperationException("EntityContext cannot be initialized multiple times.");

        var entityConnectionString = new EntityConnectionStringBuilder();
        entityConnectionString.ProviderConnectionString = connectionString;
        entityConnectionString.Provider = "System.Data.SqlClient";
        entityConnectionString.Metadata = "res://*/EntityModel.EntityModel.csdl|res://*/EntityModel.EntityModel.ssdl|res://*/EntityModel.EntityModel.msl";

        this.EntityContext = new EntityContext(entityConnectionString.ConnectionString);
        this.EntityContext.ObjectMaterialized += EntityContext_ObjectMaterialized;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用System.Configuration类

访问App.config的所有部分

示例:

var connectString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

var stringBuilder = new SqlConnectionStringBuilder(connectString);

string UserID = stringBuilder.UserID;
string Password = stringBuilder.Password;
string catalog = stringBuilder.InitialCatalog;

的App.config

<configuration>
   <connectionStrings>
     <add name="MyConnectionString" connectionString="metadata=res://*/...........
   </connectionStrings>
</configuration>