0

Is there a way to add DbSet<TEntity> Property in DbContext class at runtime without passing through OnModelCreating ?

4
  • Why are you wanting to know? Commented May 6, 2022 at 1:54
  • You don't need a property, just call db.Set<T>(). But you do need the type defined in the model somehow. Commented May 6, 2022 at 1:55
  • What are you trying to do that would require you to do this? Commented May 6, 2022 at 2:01
  • I’m trying to add tables at runtime I succeeded to add class dynamically but I couldn’t update the DbContext class so that I can add my created class as DbSet<NewClass> Commented May 6, 2022 at 4:05

1 Answer 1

2

You can do it by dynamically creating a new type that inherits from DbContext and the use Reflection Emit to add the DbSets to this type.

It's a bit of a long solution to try and post into a response here, but here's a GitHub link to a working demo of how it can be done

EF Core Dynamic Db Context

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.