Yves Calaci
Yves Calaci

Reputation: 1129

EF6: generic DbConfiguration for different DbContexts

I just updated from EF5 to EF6. This got me introduced to the DbConfiguration, since I needed one of these so that I wouldn't need to add EntityFramework as dependency to my other projects (solution has 8 projects). Everything was working until I decided to make my DbConfiguration class (inherited) to be generic, so that other DbContext classes could use it. After doing so, I started getting the error "Failed to create instance of type 'Repository.Contexts.ContextConfiguration`1[Repository.Contexts.GlobalContext]'. The type must not be generic."

Here's the [new] DbConfiguration:

using System.Data.Entity;
using System.Data.Entity.SqlServer;

namespace Repository.Contexts
{
    // Old impl did not have a constraint. Instead, the type was directly used in the CreateDatabaseIfNotExists's param
    public class ContextConfiguration<TContext> : DbConfiguration where TContext : DbContext
    {
        public ContextConfiguration()
        {
            SetDatabaseInitializer(new CreateDatabaseIfNotExists<TContext>());
            SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
        }
    }
}

The configuration is used as such:

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

[DbConfigurationType(typeof(ContextConfiguration<GlobalContext>))]
public class GlobalContext : DbContext
{
    // DbSets...
    // Constructor...
    // OnModelCreating...
}

Does every context have to have its own configuration in order to achieve what I'm trying to do?

Upvotes: 0

Views: 920

Answers (0)

Related Questions