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
編集 2013/02/20 22:25
したがって、追加として、次のように、上記のコードをサポートするコンストラクターを追加する部分クラスで、作成された DbContext クラスを拡張する必要があります。
public partial class YourDbContext
{
public YourDbContext(string connection) : base(connection) {}
}
このクラスは、エンティティ フレームワーク ウィザードによって生成される DbContext と同じ名前空間にある必要があります。