Add entity types after model creation in DbContext

c# dependency-injection entity-framework entity-framework-core

Question

I'm using EF Core 2 and 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 How to emit a Type in .NET Core)

  3. I add the created class to the model in the OnModelCreating method of the db context (see https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/)

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 DbContext is scoped to the request (not transient), so the DbContext called the OnModelCreating method 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.

1
0
5/10/2018 2:38:58 PM

Popular Answer

You would also need a new DbContext subtype, as OnModelCreating only runs once per DbContext type per AppDomain.

0
5/10/2018 5:26:18 PM


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