首页 > 其他分享 >Winform使用EFCore的CodeFirst(注入方式)

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

时间:2023-04-25 23:23:02浏览次数:43  
标签:CodeFirst serviceProvider MyDbContext var json EFCore services using Winform

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));
        }
    }
}

 

标签:CodeFirst,serviceProvider,MyDbContext,var,json,EFCore,services,using,Winform
From: https://www.cnblogs.com/smj-7038/p/17298915.html

相关文章

  • 文字反向输出:WinForm实现
    文字反向输出WinForm实现:附件是文字反向输出程序,及源代码;https://files.cnblogs.com/files/yellow3gold/WordReverse.zip......
  • abp(net core)+easyui+efcore实现仓储管理系统——组织管理升级之下(六十二)
    Abp(netcore)+easyui+efcore实现仓储管理系统目录abp(netcore)+easyui+efcore实现仓储管理系统——ABP总体介绍(一)abp(netcore)+easyui+efcore实现仓储管理系统——解决方案介绍(二)abp(netcore)+easyui+efcore实现仓储管理系统——领域层创建实体(三) abp(netcore)+eas......
  • winform设置背景图闪屏问题解决
    直接将以下代码复制粘贴到出现闪屏的窗体中即可:#region解决添加背景图片时闪屏的问题protectedoverrideCreateParamsCreateParams{get{CreateParamscp=base.CreateParams;cp.Ex......
  • WinForm快速开发框架-ZianWinForm
    WinForm快速开发框架-ZianWinForm介绍ZianWinForm是基于C#WinForm快速开发框架UI组件采用***。ORM框架采用PersistenceLayer。内嵌简单的IOC框框,支持特性:Autowired、Bean、Component,待支持特性:Configuration、ConfigurationProperties、Controller、PathVariable、PostCon......
  • Winform DataGridView使用最佳方法
    一般使用到DataGridView控件的都是涉及到多数据显示及更改。非数据库最好使用一个类写个model:internalclassDataModel{publicintid{get;set}publicstringname{get;set}publicstringtel{get;set}…… } 然后在DataGridView数据绑定此对象重新加载数据的时候......
  • 界面控件DevExpress WinForm的垂直网格组件,让数据展示更灵活!
    DevExpressWinForm VerticalGrid(垂直网格)组件设计用于提供UI灵活性,它允许显示数据集中的单个行,或在其90度反向网格容器中显示多个数据集行。此外,开发者还可以将其用作属性网格,就像在VisualStudioIDE中找到的那样。PS:DevExpressWinForm拥有180+组件和UI库,能为WindowsForms......
  • winform panel动态添加textbox控件
    //控件宽高intcontrol_w=159;intcontrol_h=55;//间隔距离intinterval_x=20;intinterval_y=20;//列可放置数量introw_count=3;///<summary>///动态加载人员选择框......
  • 【C#新手入门一】winform实现QQ登录窗口
    闲来无事,打算写一系列winform入门相关的小软件,算是对自己技术的一个复习和备忘,也希望能帮助刚入门的萌新(可能也帮不到,因为没有注释)第一期先用winform最大限度的还原QQ的登录界面,下图左侧是仿真的,右侧是QQ的界面,很明显能看出来高仿的和正版的区别,哈哈! 这是效果展示接下来......
  • C#Winform窗体操作类&控件属性类
    WinForm磁性窗体吸附边缘1#region磁性窗体23publicclassMagneticManager4{5publicclassChildFormInfo6{7publicFormChild{get;set;}8publicMagne......
  • abp(net core)+easyui+efcore实现仓储管理系统——模块管理升级之上(六十一)
     Abp(netcore)+easyui+efcore实现仓储管理系统目录abp(netcore)+easyui+efcore实现仓储管理系统——ABP总体介绍(一)abp(netcore)+easyui+efcore实现仓储管理系统——解决方案介绍(二)abp(netcore)+easyui+efcore实现仓储管理系统——领域层创建实体(三) abp(netcore)+e......