Asp.net-mvc – Multiple DbContext, multiple Database.SetInitializer

asp.net-mvcentity-framework-4

I have created two DbContexts, one is for application configuration, the second is for logging.

The reason being, I want to set a maximum size on the logging db so it doesn't use up all free disk space and prevent other databases from working.

In my global.asax.cs file, I have the following:

        protected void Application_Start()
    {

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        Database.SetInitializer<AdminContext>(new AdminInitialiser());
        Database.SetInitializer<LoggingContext>(new LoggingInitialiser());
    }

The InitializeDatabase method in LoggingInitialiser is not being called. Is this because only one initializer can be set? Is there any way to have initializers for two DbContexts?

Best Answer

Set the initializer in the DbContext constructor instead.

public class AdminContext : DbContext
{
    public AdminContext()
    {
        Database.SetInitializer(new AdminInitialiser());
    }
}

public class LoggingContext : DbContext
{
    public LoggingContext()
    {
        Database.SetInitializer(new LoggingInitialiser());
    }
}
Related Topic