十年河东,十年河西,莫欺少年穷
学无止境,精益求精
1、新建控制台项目PostgreSQLApp,引入如下包
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.32"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.32" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.32" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.32" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.32" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.32" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.32" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.18" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.0" /> </ItemGroup> <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup> </Project>View Code
2、打开PostgerSQL 新建test 数据库 并先建两张表
表的结构不重要
3、打开程序包管理器控制台,生成DbContext 及 Models
Scaffold-DbContext -Connection "User ID=postgres;Password=chen1234;Host=127.0.0.1;Port=5432;Database=test;Pooling=true;" -Provider Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models -ContextDir Context -Context postgerSqlDbContext -force
4、添加配置文件appsettings.json,并设为始终复制
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "postgerSqlDbContext": "User ID=postgres;Password=chen123456789;Host=127.0.0.1;Port=5432;Database=test;Pooling=true;" } }
5、初始化Program.cs
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using PostgreSQLApp.Context; using System; namespace PostgreSQLApp { class Program { static void Main(string[] args) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json", true, true); var ConfigRoot = builder.Build();//根节点 IServiceCollection Services = new ServiceCollection(); Services.AddLogging(log => { log.AddConsole(); log.SetMinimumLevel(LogLevel.Information); }); Services.AddScoped<UserService>(); Services.AddDbContext<postgerSqlDbContext>(options => options.UseNpgsql(ConfigRoot.GetConnectionString("postgerSqlDbContext")), ServiceLifetime.Scoped) ; using (ServiceProvider provider = Services.BuildServiceProvider()) { var UserServiceDto = provider.GetService<UserService>(); UserServiceDto.AddData(); // } CreateHostBuilder(args).Run(); } public static IHost CreateHostBuilder(string[] args) { var builder = Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<MyWindowService>(); }).UseWindowsService(); var host = builder.Build(); return host; } } }View Code
6、UserService.cs 插入/查询数据
using PostgreSQLApp.Context; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PostgreSQLApp { public class UserService { public void AddData() { using (var context = new postgerSqlDbContext()) { List<PostgreSQLApp.Models.Sysuser> users = new List<Models.Sysuser>(); List<PostgreSQLApp.Models.Userbuyrecord> buyrecords= new List<Models.Userbuyrecord>(); for (int i = 0; i < 10000; i++) { PostgreSQLApp.Models.Sysuser user = new Models.Sysuser() { Createtime = DateTime.Now, Userid = Guid.NewGuid().ToString(), Username = "陈大六" + i, Usersex = i % 2 }; users.Add(user); // PostgreSQLApp.Models.Userbuyrecord buyrecord = new Models.Userbuyrecord() { Createtime = DateTime.Now, Recordid = Guid.NewGuid().ToString(), }; buyrecords.Add(buyrecord); } context.Sysuser.AddRange(users); context.Userbuyrecord.AddRange(buyrecords); context.SaveChanges(); Console.WriteLine("插入成功"); } } public List<PostgreSQLApp.Models.Userbuyrecord> SearchData() { using (var context = new postgerSqlDbContext()) { return context.Userbuyrecord.ToList(); } } } }View Code
7、MyWindowService.cs 定时服务
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PostgreSQLApp { public class MyWindowService : BackgroundService { private readonly ILogger<MyWindowService> _logger; public MyWindowService(ILogger<MyWindowService> logger) { _logger = logger; } public override Task StartAsync(CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { } return base.StartAsync(cancellationToken); } /// <summary> /// 每一秒执行一次 /// </summary> /// <param name="stoppingToken"></param> /// <returns></returns> protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { //循环执行 每一小时执行一次 var now = DateTime.Now; Console.WriteLine("ExecuteAsync执行结果:" + now); //var data = new UserService().SearchData(); //Console.WriteLine(JsonConvert.SerializeObject(data)); await Task.Delay(1000 * 60 * 60, stoppingToken); } } public override Task StopAsync(CancellationToken cancellationToken) { return base.StopAsync(cancellationToken); } } }View Code
以上便完成了netCore 引入PostgerSql
补充下sqlserver 的DbFirst
Scaffold-DbContext -Connection "Data Source=127.0.0.1;Initial Catalog=ChargeDBTest;Password=Ws1245689;User ID=sa;MultipleActiveResultSets=true;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Context -Context swapDbContext -force
@天才卧龙的博客
标签:PostgerSql,System,new,public,PostgreSQLApp,DbFirst,using,Microsoft,NetCore3.1 From: https://www.cnblogs.com/chenwolong/p/18053853