【问题标题】:Entity Framework Core with WPF Core - Cannot add migrations带有 WPF 核心的实体框架核心 - 无法添加迁移
【发布时间】:2020-05-30 05:59:30
【问题描述】:

最近我将我的 WPF 应用程序 (.NET 4.7) 迁移到了 .Net Core 3.1。除了我无法生成/添加 EF Core 迁移之外,大部分都可以正常工作。

我在以下帖子的帮助下使用依赖注入集成了我的 dbContext / EF Core:

数据库已连接并且工作正常。但是,当我尝试通过键入以下命令来添加迁移时:Add-Migration InitialMigration 我不断收到以下错误:

无法创建“MyDBContext”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728

在 Web 应用程序中,这似乎是一个常见/已知问题,可以通过在程序类中将 CreateHostBuilder 更改为 BuildWebHost 来解决; https://stackoverflow.com/questions/57745481/unable-to-create-an-object-of-type-mycontext-for-the-different-patterns-suppo

我还通过在options.UseSqlServer 中添加MigrationsAssembly 找到了一些其他帖子。

长话短说,我尝试了所有这些解决方案,但似乎都没有奏效。可能是因为我的应用程序不是 Web 应用程序(没有程序类,例如 BuildWebHost),而是 WPF(核心)应用程序。

我的 WPF 应用程序的初始化代码如下所示:

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; }
}

任何线索哪里出错了?

【问题讨论】:

    标签: c# wpf entity-framework wpf-core-3.0


    【解决方案1】:

    刚刚看到这个帖子:WPF with entity framework on net core - unable to create and object of type AppDbContext

    解决了同样的问题。有趣的是,我并没有在我的 DuckDuckGo 搜索引擎中将其作为搜索结果,但它是我的谷歌搜索引擎中的第一个热门......

    【讨论】:

      【解决方案2】:

      对于.net core 5(不确定它是否适用于早期版本)

      只需将此类添加到您的项目中

      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);
          }
      }
      

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

      【讨论】:

        猜你喜欢
        • 2020-06-21
        • 2019-02-25
        • 2021-06-27
        • 2021-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-28
        • 2017-04-06
        相关资源
        最近更新 更多