简体   繁体   中英

Entity Framework Core with WPF Core - Cannot add migrations

Recently I migrated my WPF app (.NET 4.7) to .Net Core 3.1. Most of it works fine except for me not being able to generate/add EF Core migrations.

I integrated my dbContext / EF Core with help of the following post(s) using Dependency Injection:

The database connects and is working properly. However when I try to add migrations by typing in the following command: Add-Migration InitialMigration I keep getting the following error:

Unable to create an object of type 'MyDBContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

In web applications this seems to be a common/known issue and is fixable by changing CreateHostBuilder to BuildWebHost in the program class; https://stackoverflow.com/questions/57745481/unable-to-create-an-object-of-type-mycontext-for-the-different-patterns-suppo

I also found some other posts by adding MigrationsAssembly in options.UseSqlServer .

Long story short, I tried all these solutions but none of them seem to work. Probably because my application is not a web application (no program class eg BuildWebHost) but a WPF (Core) application.

My initializing code for the WPF app looks as following:

App.xaml.cs

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

    public App()
    {
        host = Host.CreateDefaultBuilder()
               .ConfigureServices((context, services) =>
               {
                   ConfigureServices(services);
               }).Build();
    }

    private void ConfigureServices(IServiceCollection services)
    {
        // services for DI...

        services.AddDbContext<MyDbContext>
            (options => 
                options.UseSqlServer(
                        Configuration.GetConnectionString("SqlConnection")));

        services.AddTransient<MainWindow>();
    }

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

        Configuration = builder.Build();

        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        ServiceProvider = serviceCollection.BuildServiceProvider();

        var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
        mainWindow.Show();
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        using (host)
        {
            await host.StopAsync(TimeSpan.FromSeconds(5));
        }

        base.OnExit(e);
    }
}

MyDbContext.cs

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
        Database.Migrate(); 
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Zonnescherm Model
        modelBuilder.Entity<Zonneschermen>().Property(e => e.BreedteZonnescherm).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<Zonneschermen>().Property(e => e.UitvalDoek).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<Zonneschermen>().Property(e => e.ArmLengte).HasColumnType("decimal(17,2)");

        // ScreenRegels Model
        modelBuilder.Entity<ScreenRegels>().Property(e => e.Breedte).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<ScreenRegels>().Property(e => e.Hoogte).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<ScreenRegels>().Property(e => e.DraaistangLengte).HasColumnType("decimal(17,2)");

        // Seed
        modelBuilder.Entity<Instellingen>().HasData(
            // seeding...

        );

        // Seed 
        modelBuilder.Entity<ZonneschermInstellingen>().HasData(
            // seeding...
        );

        // Seed 
        modelBuilder.Entity<ScreenInstellingen>().HasData(
            // seeding...
        );
    }

    public DbSet<Lamellen> Lamellen { get; set; }
    public DbSet<LamellenRegels> LamellenRegels { get; set; }
    public DbSet<Zonneschermen> Zonneschermen { get; set; }
    public DbSet<ZonneschermInstellingen> ZonneschermInstellingen { get; set; }
    public DbSet<Screens> Screens { get; set; }
    public DbSet<ScreenRegels> ScreenRegels { get; set; }
    public DbSet<ScreenInstellingen> ScreenInstellingen { get; set; }
    public DbSet<Instellingen> Instellingen { get; set; }
}

Any clues where it goes wrong?

Just came across this post: WPF with entity framework on net core - unable to create and object of type AppDbContext

which addresses the same issue. Funny enough I did not get this as a search result in my DuckDuckGo search engine but it was the first hit in my google search engine...

for .net core 5 (not sure if it's work for earlier version)

just add this class to your project

public class BloggingContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer("your connection string",
                options => options.EnableRetryOnFailure());

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

documentation link https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM