2

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.

4
  • So to clarify, when you do something like DbContext.NewEntityClass.Add(UserCreatedEntity) it fails because the context has no existing definition of the NewEntityClass? So you're trying to dynamically create new entity classes within your DbContext through user input? Commented May 10, 2018 at 14:15
  • That's correct. I updated the question with the error that I get when I do DbContext.NewEntityClass.Add(UserCreatedEntity). Commented May 10, 2018 at 14:41
  • the modelbuilder is not accessible from outside, and it wouldn't do anything on a context instance anyways. your model has to be defined once you create the context type you want to use to access this model, there's no way around that. Commented May 10, 2018 at 15:55
  • What about requesting a new DbContext instance after the entity has been added? Is there a way to do that for a scoped service? I add the context this way: services.AddDbContext<MyDbContext>(), which is equivalent to a ServiceLifetime.Scoped lifetime. Commented May 10, 2018 at 16:01

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

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.