Add entity types after model creation in DbContext
I'm trying to add an entity dynamically to the the model. The scenario is: 1- The user creates an entity with custom properties in a web app 2- I create at runtime a class that maps this entity (see this) 3- I add the created class to the model in the OnModelCreating method of the DbContext (see this)
Everything works, except when I want to write to the db a new instance of the newly created class in the same request (API call) where I created the new entity. This is because the OnModelCreating method gets called only once, before I had the chance to create the new entity.
This is the error that I get:
The entity type 'People' was not found. Ensure that the entity type has been added to the model.
Any suggestions on how to accomplish that? I don't think it's possible to call OnModelCreating on demand and I can't find a way to access the ModelBuilder of the context to call it's Entity method.
EF Core version: 2.1.0-rc1-final Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Windows 10 IDE: Visual Studio 2017 15.7.1
You can create the model "outside" of the DbContext by calling UseModel. To make this work you will need to build the DbContext outside of DI so you can build the model dynamically as part of the request (this normally happens during start-up)
@enrichz The model cannot be mutated while it is being used, but you can force OnModelCreating to run again and build a new model by controlling the model cache key--see https://docs.microsoft.com/en-us/ef/core/modeling/dynamic-model. However, note that this is an expensive thing to do, and doing it many times will result in many different models being built and cached, which will affect performance significantly.
@anpete That's a very interesting approach. So you mean that I don't have to register the DbContext in the ServiceProvider but create it when I need it (new DbContext()) ? Also, I would appreciate a small example on how to create a Model outside OnModelCreating method. I'm using the configuration approach (modelBuilder.ApplyConfiguration(IEntityTypeConfiguration conf)) and also I have annotations in my entity classes, how can I translate this into the ConventionSet used to build the model?
@ajcvickers Thank you for this tip, this way I can solve my next problem, which is to force a model refresh after adding a new entity.