.NETCore环境下Windows Form程序,DI方式使用DbContext并读取配置文件
1、创建项目。选择Windows Form App(.NET) 模板创建
2、新建配置文件,取名appsettings.json
3、添加如下配置,自动生成的可以删除,注意 appsettings.json 文件属性一定要设置始终复制
{
"ConnectionStrings": {
"PCBPTS_Test": "Data Source=.;Initial Catalog=PCBPTS_Test;user=sa;pwd=123123;Integrated Security=True;Pooling=true;MultipleActiveResultSets=True;"
}
}
4、添加实体类并添加DbContext类,DbContext类如下,
需要引入Nuget包: Microsoft.EntityFrameworkCore.SqlServer
using Microsoft.EntityFrameworkCore; namespace NET5WinformDemo { public class PCBPTSContext : DbContext { public PCBPTSContext(DbContextOptions<PCBPTSContext> options) : base(options) { } public virtual DbSet<User> User { get; set; } } }
5、接下来就是为项目添加DI ,代码如下。打开Program.cs文件,修改Main方法
需要引入Nuget包: Microsoft.Extensions.Configuration.Json
static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //添加 json 文件路径,注意 appsettings.json 文件属性一定要设置始终复制 var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); var config = builder.Build(); //添加DI var services = new ServiceCollection(); services.AddOptions(); services.AddSingleton(config); //配置连接字符串 services.AddDbContext<PCBPTSContext>( option => option.UseSqlServer(config.GetConnectionString("PCBPTS_Test")) ); //添加主窗体为单例 services.AddSingleton(typeof(Form1)); Application.Run(services.BuildServiceProvider().GetRequiredService<Form1>()); }
6、主窗体构造函数注入PCBPTSContext
private readonly PCBPTSContext _PCBPTSContext; public Form1(PCBPTSContext PCBPTSContext) { InitializeComponent(); _PCBPTSContext = PCBPTSContext; List<User> Users = _PCBPTSContext.User.ToList(); }
好记性不如烂笔头, We grow up together