在WPF中使用EFCore Migration
在WPF(.NET5)中使用EFCore进行数据迁移的障碍主要是EFCore无法创建DbContext,通过实现IDesignTimeDbContextFactory接口可以通过自主创建DbContext,解决EFCore找不到数据库上下文的问题。
参考资料:WPF with entity framework on net core - unable to create and object of type AppDbContext
本文的环境为:WPF + .NET5 + EF Core + SQLite。
1、DesignTimeDbContextFactory
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<SqliteDbContext> { public SqliteDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<SqliteDbContext>(); optionsBuilder.UseSqlite("Data Source=Data.db"); return new SqliteDbContext(optionsBuilder.Options, null); } }
2、SqliteDbContext
public class SqliteDbContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<UserRole> UserRoles { get; set; } private readonly string _connectionString; // ReSharper disable once IdentifierTypo public SqliteDbContext(DbContextOptions<SqliteDbContext> options, IConfigService configService) : base(options) { _connectionString = configService?.SqliteConnectionString; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!string.IsNullOrWhiteSpace(_connectionString)) { optionsBuilder.UseSqlite(_connectionString); } optionsBuilder.UseLazyLoadingProxies(); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //添加角色 modelBuilder.Entity<UserRole>().HasData( new UserRole() {Id = 1, Name = @"user", Remark = @"普通用户"}, new UserRole() {Id = 2, Name = @"admin", Remark = @"管理员"} ); //添加用户 modelBuilder.Entity<User>().HasData( new User() { Id = 1, UserName = @"test", Password = @"123456", CreateTime = DateTime.Now, UserRoleId = 1 }, new User() { Id = 2, UserName = @"admin", Password = @"123456", CreateTime = DateTime.Now, UserRoleId = 2 } ); } }
3、注意事项
(1)IDesignTimeDbContextFactory接口的泛型必须是已定义的DbContext(比如文中的SqliteDbContext)。
(2)optionsBuilder.UseSqlite中的连接字符串必须明确定义,这里定义为常量,也可以是从配置中加载的字符串。使用其他数据库,例如MySQL,也是一样的。
(3)进行数据迁移的时候要确保安装这些包:Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.Sqlite、Microsoft.EntityFrameworkCore.Tools。
4、常用数据迁移命令
可以在程序包管理器控制台上执行数据迁移命令,当然也可以直接在命令行中执行。
(1)配置Migration
Enable-Migrations -ContextTypeName "TestWpf.SqliteDbContext" -ProjectName " TestWpf" -StartUpProjectName " TestWpf" -ConnectionStringName "Data Source=Data.db" -Verbose
(2)添加数据迁移
add-migration InitialMigration -Context LabelPrintingSystem.Database.SqliteDbContext
(3)更新数据库
update-database
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器