WPF与网络核心上的实体框架-无法创建和创建AppDbContext类型的对象

帕维尔

当我使用实体框架时,我有简单的WPF Net Core应用程序,我有DbContext,但是当我添加迁移时,我收到错误消息:

PM> add-migration init
Build started...
Build succeeded.
Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

我的appsettings.json

{
  "ConnectionStrings": {
    "SqlConnection": "Server=DESKTOP-K6R1EB3\\tester;Database=test;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

AppDbContext

using Microsoft.EntityFrameworkCore;

namespace WpfApp1
{
    public class AppDbContext : DbContext
    {
        public DbSet<Person> Person { get; set; }
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }


    }
}

App.xaml.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public IServiceProvider ServiceProvider { get; private set; }

        public IConfiguration Configuration { get; private set; }

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

        private void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>
        (options => options.UseSqlServer(
                    Configuration.GetConnectionString("SqlConnection")));

            services.AddTransient(typeof(MainWindow));
        }
    }
}

当然我有一个简单的数据库模型

namespace WpfApp1
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

怎么了?我搜索解决方案,但未找到任何结果。早期,我在网络核心和实体框架中编写Web应用程序,而且我没有任何问题。这是我的第一个WPF Net Core App,我在EF配置方面遇到问题。

柯克·霍顿

我能够重现您的问题并克服它。

我以前遇到过这个。这篇文章指导我完成了我需要做的事情,对此我感到非常感谢:https : //blog.tonysneed.com/2018/12/20/idesigntimedbcontextfactory-and-dependency-injection-a-love-story/

错误消息中的文章:https : //go.microsoft.com/fwlink/?linkid=851728特别是本节https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/cli/dbcontext-creation#from-a-design-time-factory,我们可以使用一些鸭子类型并提供一个Microsoft.EntityFrameworkCore.Tools将用于创建迁移,并实施IDesignTimeDbContextFactory<T>

tony sneed的文章提供了一个通用的抽象实现,然后我们可以非常简单地得出该实现。

这是通用的抽象实现(编辑,对不起,刚意识到我复制粘贴了我对Tony sneed的代码的修改,这是我之前遇到过的代码):

public abstract class DesignTimeDbContextFactoryBase<TContext> : IDesignTimeDbContextFactory<TContext> where TContext : DbContext
{
    public TContext CreateDbContext(string[] args)
    {
        return Create(Directory.GetCurrentDirectory(), Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
    }
    protected abstract TContext CreateNewInstance(DbContextOptions<TContext> options);
    public TContext Create()
    {
        var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        var basePath = AppContext.BaseDirectory;
        return Create(basePath, environmentName);
    }
    TContext Create(string basePath, string environmentName)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{environmentName}.json", true)
            .AddEnvironmentVariables();
        var config = builder.Build();
        var connstr = config.GetConnectionString("default");
        if (string.IsNullOrWhiteSpace(connstr) == true)
            throw new InvalidOperationException("Could not find a connection string named 'default'.");
        return Create(connstr);
    }
    TContext Create(string connectionString)
    {
        if (string.IsNullOrEmpty(connectionString))
            throw new ArgumentException($"{nameof(connectionString)} is null or empty.", nameof(connectionString));
        var optionsBuilder = new DbContextOptionsBuilder<TContext>();
        Console.WriteLine($"MyDesignTimeDbContextFactory.Create(string): Connection string: {connectionString}");
        optionsBuilder.UseSqlServer(connectionString, s => s.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds));
        DbContextOptions<TContext> options = optionsBuilder.Options;
        return CreateNewInstance(options);
    }
}

您提供AppDbContext的实现:

public class AppDbContextFactory : DesignTimeDbContextFactoryBase<AppDbContext>
{
    protected override AppDbContext CreateNewInstance(DbContextOptions<AppDbContext> options)
    {
        return new AppDbContext(options);
    }
}

Add-Migration(或从技术上来说,可能是Microsoft.EntityFrameworkCore.Tools)将检测到。

有很多nuget包要添加:

<ItemGroup>
  <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
  </PackageReference>
  <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.1" />
  <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.1" />
  <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.1" />
  <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.1" />
</ItemGroup>

一旦您克服了错误,我又遇到了一个错误:Could not find a connection string named 'default'.因此我将appsettings更改SqlConnectiondefault

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章