无法创建类型为“ AppDataContext”的对象

时间:2020-07-20 14:56:08

标签: c# wpf entity-framework

在WPF应用程序中设置迁移时遇到了一些麻烦。我有这样的DbContext类:

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

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

然后在App.xaml.cs中,我设置DI和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>();
    }

}

如果我运行命令Add-Migration Initial -verbose,则会收到以下消息:

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

由于这是我在WPF中使用EF Core 3.1的第​​一个应用程序,所以我不知道问题出在哪里。

谢谢。

1 个答案:

答案 0 :(得分:0)

您需要实现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);
    }
}

此外,我在App.xaml.cs代码中看到错误。您应该覆盖OnStartup(StartupEventArgs)方法,正确的签名应该是:

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

重要:从StartupUri文件中删除App.xaml