How to create Entity Framework ObjectContext?

theateist picture theateist · Aug 31, 2011 · Viewed 13.4k times · Source

I have many DBs in one SQL server. I placed connectionString as template(look at Initial Catalog={0}) into web.config.

<add name="ent" connectionString="metadata=res://*/ent.csdl|res://*/ent.ssdl|res://*/ent.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=1.1.1.1;Initial Catalog={0};Persist Security Info=True;User ID=user;Password=pass;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

I want to create the objectContext with correct connectionString. I thought to do the following, CreatObjectContext<SiteEntities>('MySite') but I get error Unable to determine the provider name for connection of type 'System.Data.EntityClient.EntityConnection'.

public T CreatObjectContext<T>(string dbName) where T : ObjectContext, new()
{          
       var conStr = ConfigurationManager.ConnectionStrings["ent"].ConnectionString;
       var entityBuilder = new EntityConnectionStringBuilder(conStr);
       entityBuilder.Provider = "System.Data.SqlClient";
       // Build correct conString to the db
       entityBuilder.ProviderConnectionString = string.Format(entityBuilder.ProviderConnectionString, dbName);

       var connection = new EntityConnection(entityBuilder.ConnectionString);                          
       var builder = new ContextBuilder<T>();

       return builder.Create(connection);           
}

What I'm doing wrong? How I can create the context?

Answer

Bobby Richard picture Bobby Richard · Aug 31, 2011

If you are using EntityConnectionStringBuilder, you only need to store the sqlserver connection strings in your web.config. EntityConnectionStringBuilder can then convert those to EF4 connection strings.

Example web.config

    <connectionStrings>
      <add name="db1" connectionString="data source=localhost\SQLEXPRESS;initial catalog=db1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework" /> 
      <add name="db2" connectionString="data source=localhost\SQLEXPRESS;initial catalog=db2;integrated security=True;multipleactiveresultsets=True;App=EntityFramework" />
    </connectionStrings>

And we can change your method to something like:

public ObjectContext CreatObjectContext(string dbName)
{          
       var conStr = ConfigurationManager.ConnectionStrings[dbName].ConnectionString;
       var entityBuilder = new EntityConnectionStringBuilder();

       entityBuilder.Provider = "System.Data.SqlClient";
       entityBuilder.ProviderConnectionString = conStr;

       entityBuilder.MetaData = @"res://*/ent.csdl|res://*/ent.ssdl|res://*/ent.msl";

       return new ObjectContext(entityBuilder.ToString());          
}