ASP.NET Core OnModelCreating force to fire in every request

asp.net-core-mvc c# entity-framework-core sql-server

Question

ASP.NET Core OnModelCreating force to fire in every request

I have ASP.NET Core (1.1.0) and SQL Server database. In login page I have a form with a select box with name of companies.

For example:

  • Company 1
  • Company 2

If a user selects the the first "Company 1", I need to rename all the tables with a company prefix:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    foreach (var entity in builder.Model.GetEntityTypes())
    {
       entity.Relational().TableName = "Company 1" + entity.DisplayName();
    }
}

It's working perfectly fine, but the problems is when user selects the wrong company, or logs out of the system and logs back in with a different company, OnModelCreating never gets called again and I can't reconfigure the dbContext.

Is it possible to force OnModelCreating for every request?

Or change table name after dbContext initilization?

Thanks!

1
2
1/27/2017 4:00:17 PM

Popular Answer

It's wrong way. OnModelCreating runs when EF creates/describes model from your classes. There are a lot of reflection and type manipulation here, including validating relations, comparing to real DB (and check if migrations are needed) and so on. Do you really need to run all this stuff on every request???

Do not recreate DbContext for every request. Create several DbContexts and choose one of them (created once!) at request start.

For example:

Make your main DbContext abstract, and create as many CompanyXDbContext as needed. They all should inherit from base class, providing simple table prefix to it (in ctor).

Everywhere in your code, when you need DbContext, ask for abstract/base class from DI.

In Startup, register your abstract DbContext with factory method for choosing real one depending on current Request variables/params, or write custom middleware that creates correct instance based on current Request.


If you have a LOT of CompanyX, then you may need something other instead of many pre-coded CompanyXDbContext classes, something with runtime class creating or may be generics... But main idea is still unchanged - do not recreate model again and again on every request.

0
1/30/2017 8:33:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow