【发布时间】:2012-11-29 00:12:19
【问题描述】:
一些简单的问题:
所以我有这个LogInWindow 对话框,用于收集所有 SQL 登录信息,然后将构造的连接字符串传递给 ServiceManager.InitializeContext() 方法,该方法使用特定的提供程序连接初始化我的实体上下文。
一切正常。但我想用 App.config 配置文件中定义的值初始化LogInWindow 对话框。
是否有首选方法来执行此初始设置?即,我是否应该仅出于获取默认提供程序连接的纯粹目的而使用默认构造函数实例化一个虚拟EntityContext?有没有“更清洁”的方式?
顺便说一句,您认为在Form.Shown 事件的处理程序中执行这种类型的Form.Close() 调用是一种“安全”的做法吗?我在 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;
}
}
【问题讨论】:
标签: c# .net sql-server entity-framework connection-string