【发布时间】:2020-02-10 13:42:29
【问题描述】:
当我使用实体框架时,我有简单的 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; }
}
}
怎么了?我搜索解决方案,但我什么也没找到。早期我在网络核心和实体框架中编写网络应用程序,我没有任何问题。这是我的第一个 WPF Net Core 应用程序,我的 EF 配置有问题。
【问题讨论】:
标签: wpf entity-framework .net-core