Fel*_*pez 3 entity-framework entity-framework-5
我正在开发一个类库,用于处理使用EF的现有数据库.我想避免类库(和.exe或网站)的使用者在*.config文件中包含实体连接字符串.我希望连接字符串设置为运行时.
如何使用Database First方法设置连接字符串?没有构造函数重载接受连接字符串,当我创建一个(在一个单独的分部类中)时,我得到了"UnintentionalCodeFirstException".
我已经审查过以下链接:
DbContext上有一个构造函数,它接受一个DbConnection,你需要使用一个EntityConnection对象:
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = "server name";
sqlBuilder.InitialCatalog = "database name";
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder();
// Initialize the EntityConnectionStringBuilder.
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
using(var context = new YourDbContext(entityBuilder.ToString())){
//do stuff here
}
Run Code Online (Sandbox Code Playgroud)
需要注意的重要一点是元数据部分 - 显然需要为模型名称替换"Model1".
参考:http://msdn.microsoft.com/en-us/library/bb738533.aspx
编辑20/02/2013 22:25
因此,作为补充,您需要使用部分类扩展创建的DbContext类,该部分类添加构造函数以支持上述代码,如下所示:
public partial class YourDbContext
{
public YourDbContext(string connection) : base(connection) {}
}
Run Code Online (Sandbox Code Playgroud)
此类需要与实体框架向导生成的DbContext位于同一名称空间中.
归档时间: |
|
查看次数: |
3397 次 |
最近记录: |