8

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?

3 Answers 3

9

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());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Isn't there a risk that this is going to get called multiple times? I suspect initialisation is expensive, even if there are no changes to deploy. How about if you put it in a static constructor, meaning it will only ever get called once?
4

Yes you can do it. You just need to initialize before you move on to the next one.

  Database.SetInitializer<MyDBContext>(myInitializer);
  MyDbContext context = new MyDbContext();
  context.Database.Initialize(false);

  Database.SetInitializer<MySecondDBContext>(myInitializer);
  MySecondDbContext context2 = new MySecondDbContext();
  context2.Database.Initialize(false);

Note: that I usually get the DbContext instance from a dependency resolver...

Comments

3

I suggest to put the SetInitializer call to static constructor like below:

    static ApplicationIdentityDbContext()
    {
        Database.SetInitializer(new IdentityDbInitializer());
    }

Below is from MSDN

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

So static constructor is ideal for initialize database. I have used this technique for multiple database and it works well for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.