Search code examples
c#genericsreflectiondbcontextactivator

System.MissingMethodException Constructor on type xxx not found


I have a generic method, this method will receive a dbcontext type. This generic method should create a new instance from the received context type and return it.

a Dbcontext example:

  class SchoolContext:DbContext
    {

        public SchoolContext(DbContextOptions<SchoolContext> dbContextOptions):base(dbContextOptions)
        {
            
        }

        public DbSet<Branche> Branches { get; set; }
        public DbSet<Student> Students { get; set; }
    }

What i tried:

public static TContext GetInstance<TContext>(string connectionString) where TContext:DbContext
{
    var      optionsBuilder = new DbContextOptionsBuilder();
    optionsBuilder.UseSqlServer(connectionString);
    TContext context = Activator.CreateInstance(typeof(TContext), optionsBuilder.Options) as TContext;

    return context;
}

Erros I got :

 System.MissingMethodException: 'Constructor on type 'SchoolContext' not found.'

so please how I can fix this issue ?


Solution

  • Almost there. You just need to start with a DbContextOptionsBuilder<TContext> to create a DbContextOptions<SchoolContext> for the constructor, like this:

    public static TContext GetInstance<TContext>(string connectionString) where TContext : DbContext
    {
        var optionsBuilder = new DbContextOptionsBuilder<TContext>();
        optionsBuilder.UseSqlServer(connectionString);
        TContext context = (TContext)Activator.CreateInstance(typeof(TContext), optionsBuilder.Options);
    
        return context;
    }