derstauner
derstauner

Reputation: 1806

Unable to create an object of type 'AppDataContext'

I'm having some troubles setting up a migration in a WPF app. I have the DbContext class like this:

    public class AppDataContext : DbContext
{
    public AppDataContext(DbContextOptions<AppDataContext> options) : base(options) { }

    public DbSet<Capacity> Capacities { get; set; }
    public DbSet<CapacityType> CapacityTypes { get; set; }
}

Then in the App.xaml.cs I set up DI and IoC:

    public partial class App : Application
{
    public IServiceProvider ServiceProvider { get; private set; }
    public IConfiguration Configuration { get; private set; }

    private void OnStartUp(object sender, StartupEventArgs e)
    {
        var ConfigBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        Configuration = ConfigBuilder.Build();

        ServiceCollection Services = new ServiceCollection();
        ConfigureServices(Services);
        ServiceProvider = Services.BuildServiceProvider();

        MainWindow MainWindow = ServiceProvider.GetService<MainWindow>();
        MainWindow.Show();
    }

    private void ConfigureServices(IServiceCollection Services)
    {
        Services.AddDbContext<AppDataContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("ProdToolDb"));
        });

        Services.AddSingleton<MainWindow>();
    }

}

If I run the command Add-Migration Initial -verbose, I get this message:

Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'AppDataContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'AppDataContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.MissingMethodException: No parameterless constructor defined for type 'ProdTool.Models.AppDataContext'.
   at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'AppDataContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

As this is my first app in WPF with EF Core 3.1, I can't figure out, what the problem is.

Thank you.

Upvotes: 2

Views: 3400

Answers (1)

denys-vega
denys-vega

Reputation: 3697

You need to implement a Design Time DbContext

public class AppDataContextFactory : IDesignTimeDbContextFactory<AppDataContext>
{
    public AppDataContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<AppDataContext>();
        var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        optionsBuilder.UseSqlServer(config.GetConnectionString("ProdToolDb"));

        return new AppDataContext(optionsBuilder.Options);
    }
}

Also, I see an error in App.xaml.cs code. You should override the OnStartup(StartupEventArgs) method, the correct signature should be:

protected override void OnStartup(StartupEventArgs e)
{
    var ConfigBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    ...
}

Important: Remove the StartupUri from App.xaml file.

Upvotes: 2

Related Questions