efcore 的同步方法

打开 程序包管理器控制台
cd 项目根目录(比如 cd C:\Users\Administrator\source\repos\WpfApp2\WpfApp2 回车)

dotnet ef migrations add AddLoginTable
(如果报错:"No executable found matching command 'dotnet-ef'" 就运行:dotnet tool install --global dotnet-ef)

dotnet ef database update

如果没有完整的记录,dotnet ef migrations add AddLoginTable 每次都会生成所有表的更新,所以需要保留
__EFMigrationsHistory表的记录和项目里自动生成的Migrations文件夹和AppDbContextModelSnapshot.cs,另一个时间名的文件用完后再删掉)

新增类和修改类都一样的操作,软件会自动处理

---------------------------------------------------------------------

主要类:App.xaml.cs

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

namespace WpfApp2
{
    public partial class App : Application
    {
        public IServiceProvider ServiceProvider { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            var services = new ServiceCollection();

            // 配置连接字符串
            var connectionString = "Server=.\\mssqlserver2016;Database=StudentsData;User Id=sa;Password=123456;TrustServerCertificate=True";

            // 注册 DbContext
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(connectionString));

            // 注册其他服务
            services.AddTransient<MainWindow>();

            ServiceProvider = services.BuildServiceProvider();

            //// 创建并显示主窗口
            var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();


            mainWindow.Show();
        }
    }
}
//Db类

using
Microsoft.EntityFrameworkCore; namespace WpfApp2 { public class AppDbContext : DbContext { public static object lockobj = new object(); public DbSet<Login> Logins { get; set; } public DbSet<User> Usera { get; set; } // 构造函数接受 DbContextOptions 并传递给基类 public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } } }

窗体:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static IServiceScopeFactory serviceScopeFactory = null;

        public MainWindow()
        {
            InitializeComponent();

            serviceScopeFactory = ((App)Application.Current).ServiceProvider.GetRequiredService<IServiceScopeFactory>();

            Task.Run(() =>
            {
                while (true)
                {
                    lock (AppDbContext.lockobj)
                    {
                        using (var scope = serviceScopeFactory.CreateScope())
                        {
                            var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>(); // 子线程专属实例
                            var l = dbContext.Logins.ToList();
                            var temp = l.First();
                            temp.UserName = "333333";
                            dbContext.SaveChanges();

                        }
                    }
                }
            });
        }
    }
}

工厂类,用于执行命令时报错用:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace WpfApp2
{
    // 设计时工厂类,用于 EF Core 工具创建 DbContext
    public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            // 配置连接字符串(与 App.xaml.cs 中的一致)
            var connectionString = "Server=.\\mssqlserver2016;Database=StudentsData;User Id=sa;Password=123456;TrustServerCertificate=True";

            var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
            optionsBuilder.UseSqlServer(connectionString);

            return new AppDbContext(optionsBuilder.Options);
        }
    }
}

 

posted on 2025-07-07 00:09  海湾的贝壳  阅读(9)  评论(0)    收藏  举报