简体   繁体   中英

ASP.NET Core OnModelCreating force to fire in every request

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM