Ari*_*ian 5 c# linq asp.net entity-framework c#-4.0
我有一个具有4个实体数据模型的项目,要构建它们,我不想在我的项目中保存连接字符串,而是要将连接字符串存储在app.config
文件中并在我的模型之间共享,我该怎么做?
谢谢
假设首先是 DbContext 和模型/数据库。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
派生上下文的代码不会改变,只是它们必须继承自 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);
}
Run Code Online (Sandbox Code Playgroud)