Entity Framework Core how to instantiate DBContext using reflection?

I have a NET 7 console app using EF core, I have a situation where I need to instantiate my custom DB Context classes using reflection passing in a DBContextOptions parameter.

I am getting the following error when calling Invoke().

Cannot convert DbContextOptions`1 to DbContextOptions`1

Sample code is as follows:

public T CreateDBContext<T>(DbContextOptions dbOpts) 
{
    ConstructorInfo[] ci = typeof(T).GetConstructors().Where(c => c.GetCustomAttributes(typeof(DbContextOptions), true) != null).ToArray(); // returns 1 item
    var result = ci[0].Invoke(new object[] {dbOpts}); // Exception here.
{

The DbContext is defined as follow:-

class MyContext : DbContext
{
   public MyContext() {...}
   public MyContext(DBContextOptions<MyContext> options) : base(options) {...}
}

When I check the value of CI I can see the parameter DbContextOptions is defined as nullable (optional). Just wondering what I am missing?

Regards

I had declared my function incorrectly.

I ended up with

public T CreateDBContext<T>(...) where T : DbContext
{
    DbContextOptionsBuilder optBuilder = new DbContextOptionsBuilder<T>();
    ... 
    var result = ci[0].Invoke(new object[] {optBuilder.Options});
    ...
}

The fix was to add the where on the end of the function definition, which enabled me to then declare the options builder of the appropriate type.

Leave a Comment