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
}
需要注意的重要一点是元数据部分 - “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) {}
}
此类需要与实体框架向导生成的 DbContext 位于同一命名空间中。