Winform使用EFCore的CodeFirst(注入方式)

发布时间 2023-04-25 23:22:32作者: 关心千九

1、新建项目

  使用vs创建一个winform的项目,这里就不演示了。

2、拉取nuget包

  获取配置:Microsoft.Extensions.Configuration.Json
  注入:Microsoft.Extensions.DependencyInjection
  mysqlEF:MySql.EntityFrameworkCore

  

3、创建appsettings.json配置文件

  在项目根目录创建appsettings.json,并在里面配置数据库链接。

{
  "ConnectionStrings": {
    "MysqlConnectionString": "server=127.0.0.1;port=3306;database=xxxx;uid=root;password=xxxx;CharSet=utf8"
  }
}

  

  注意:appsettings.json 文件属性一定要设置始终复制

  

4、新增MyDbContext类

  新建MyDbContext类,继承DbContext

public class MyDbContext : DbContext
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="options"></param>
        public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
        {

        }

        /// <summary>
        /// User用户表
        /// </summary>
        public DbSet<User> User{ get; set; }
    }

5、在main函数中切入mysql配置

  main函数在Program.cs文件中,具体代码如下图,其中包含了的注入的方式,请自行斟酌代码

  余下的就和正常使用ef一样,创建entity,并在MyDbContext创建DbSet,然后就可以注入使用了。

using LiteWorkflow.Service;
using LiteWorkflow.Service.Impl;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace LiteWorkflow
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();

            // 添加 json 文件路径,注意 appsettings.json 文件属性一定要设置始终复制
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            var config = builder.Build();

            // 创建服务容器
            var services = new ServiceCollection();
            // 添加服务注册
            ConfigureServices(services);
            // 添加MyDbContext注入
            services.AddDbContext<MyDbContext>(
                option =>
                    {
                        option.UseMySQL(config.GetConnectionString("MysqlConnectionString") ?? string.Empty);
                        // option.EnableServiceProviderCaching(false);
                    }
                );

            //先用DI容器生成 serviceProvider, 然后通过 serviceProvider 获取Main Form的注册实例
            var serviceProvider = services.BuildServiceProvider();

            // 创建 DbContext 实例并执行数据库迁移
            //using (var context = serviceProvider.GetService<MyDbContext>())
            //{
            //    // 数据库不存在自动创建
            //    context?.Database.EnsureCreated();
            //}
            //主动从容器中获取FormMain实例, 这是简洁写法
            var formMain = serviceProvider.GetRequiredService<Form1>();
            Application.Run(formMain);
        }

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureServices(IServiceCollection services)
        {
            //批量注入可以使用Scrutor或者自己封装
            services.AddScoped<IWorkFlowService, WorkFlowService>();
            services.AddScoped<IWorkFlowDefService, WorkFlowDefService>();

            services.AddScoped(typeof(Form1));
            services.AddScoped(typeof(WKDefForm));
        }
    }
}