所以我在 EF 中的迁移方面遇到了问题。我正在尝试熟悉一个较旧的 WPF 项目,并且我已经进行了一些重组。我将 Context 移至具有通用代码的类库
namespace WPFDemoApp.Common.Context
{
public class ApplicationDbContext<TEntity> : DbContext where TEntity : class
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext<TEntity>> options)
: base(options)
{
}
public DbSet<TEntity> Entities { get; set; }
}
public class ApplicationDbContextFactory<TEntity> : IDesignTimeDbContextFactory<ApplicationDbContext<TEntity>> where TEntity : class
{
public ApplicationDbContext<TEntity> CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext<TEntity>>();
optionsBuilder.UseSqlite("Data Source=localdatabase.db");
return new ApplicationDbContext<TEntity>(optionsBuilder.Options);
}
}
}
它注册在不同的项目中
namespace WPFDemoApp
{
public static class ServiceRegistration
{
public static IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
// Register services here
services.AddDbContext<ApplicationDbContext<ToDoItem>>(
options => options.UseSqlite("Data Source=localdatabase.db"));
services.AddScoped<MainWindow>();
services.AddScoped<ToDoItem>();
services.AddScoped<IRepository<ToDoItem>, Repository<ToDoItem>>();
services.AddScoped<IGetAllDataUseCase<ToDoItem>, GetAllDataUseCase<ToDoItem>>();
services.AddScoped<MainViewModel<ToDoItem>>();
// Add other services
return services.BuildServiceProvider();
}
}
}
当我使用
我尝试过运行不同的命令,但旧的 WPF 结构让我头疼。
使用非通用 DbContext 进行迁移
namespace WPFDemoApp.Common.Context
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<ToDoItem> ToDoItems { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Apply configurations here if any
}
}
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("Data Source=localdatabase.db");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
}
修改服务注册: 在您的 DI 容器中注册非通用 ApplicationDbContext:
namespace WPFDemoApp
{
public static class ServiceRegistration
{
public static IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
// Register services here
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlite("Data Source=localdatabase.db"));
services.AddScoped<MainWindow>();
services.AddScoped<ToDoItem>();
services.AddScoped<IRepository<ToDoItem>, Repository<ToDoItem>>();
services.AddScoped<IGetAllDataUseCase<ToDoItem>, GetAllDataUseCase<ToDoItem>>();
services.AddScoped<MainViewModel<ToDoItem>>();
// Add other services
return services.BuildServiceProvider();
}
}
}
运行迁移:
添加-迁移InitialCreate -Project YourProjectName -StartupProject YourStartupProjectName -Context ApplicationDbContext