How to manage connections when using DbModelBuilder in Entity Framework?

1.6k Views Asked by At

I am writing an IRepository and IUnitOfWork wrapper for an EF4 Fluent schema.

In this design, a DbCompiledModel is created once per application lifecycle (Like an NHibernate ISessionFactory). The DbCompiledModel expects an existing database connection, as do all DbContexts.

This is the DbCompiledModel factory:

public class DbCompiledModelFactory
{
    public static DbCompiledModel Build(
        string mappingAssembly, DbConnection connection)
    {
        DbModelBuilder modelBuilder = new DbModelBuilder();
        AddMappingsFromAssembly(modelBuilder, mappingAssemblyName);
        DbModel model = modelBuilder.Build(connection);
        return model.Compile();
    }
}

Once the DbCompiledModel is created, a new DbContext can be created using new DbContext(connection, compiledModel, true)

So I am faced with two choices: Either share one DbConnection through the whole application lifecycle or create a shortlived DbConnection just for the model building process, and a new DbConnection whenever a DbContext is created.

Is there a more effective way of managing connections that I have overlooked?

1

There are 1 best solutions below

0
Ladislav Mrnka On

The connection itself is only needed to identify ADO.NET provider and manifest token. The Build method has overloaded version accepting DbProviderInfo instance. This overload is internally called by the overload accepting DbConnection. So you can call the version with DbProviderInfo directly if you don't like the one with DbConnection.

Don't use EF if you know that you will need another ORM later. Designing application to support multiple ORMs is only possible if you know uppfront all of them and design your application in the way that it uses only shared features among them. IMHO support more then one ORM is never needed and replacing ORM always means changes to application.