首页 > 数据库 >NetCore3.1 引入PostgerSql + DbFirst

NetCore3.1 引入PostgerSql + DbFirst

时间:2024-03-05 13:47:01浏览次数:30  
标签:PostgerSql System new public PostgreSQLApp DbFirst using Microsoft NetCore3.1

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

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

相关文章

  • .Net 6/NetCore3.1 Vue Element Uniapp前后端分离低代码快速开发框架
    .Net6/NetCoreVueElementUniapp前后端分离低代码快速开发框架这是一个能提高开发效率的开发框架,全自动生成PC与移动端(uniapp)代码;支持移动ios/android/h5/微信小程序。一、框架能做什么1、前后端分离项目2、纯后端项目3、移动端开发uni-app(IOS、Android、H5、微信小程......
  • Asp.NetCore3.1
     Asp.NetCore3.1.NetCoreFramework都属于框架并列:大家是不同的框架,都有自己的CLR。Asp.NetCore是一套Web开发框架 https://github.com/aspnet/AspNetCore 源码地址            1 ......
  • 从.net Framework4.6WPF升级到.netcore3.1/net5/6/7.0版本
    因项目需要,需将.netFramework4.6WPF升级到.netcore3.1/net5.0/6.0/7.0版本,通过很多办法解决,开始搞得一头雾水。终于,找到了办法。1、首先下载upgrade-assistant工具(.net升级......
  • EF Core DBFirst
    只要不是初创公司,哪家还没个老项目,所以DBFirst还是很有用武之地的1.首先创建一个空的创建一个ASP.NETCoreWeb应用(类库也行)DDD模式放在Domain中比较好2.引入包,在程序包......
  • 沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
    .Net6是继.NetCore3.1之后的有一LTS长期支持版本,我们一般会将.NetCore3.1项目直接升级到.Net6,网上有很多人说,需要先从.NetCore3.1升级到.Net5,再升级到.Net6,其实我觉得直接......
  • .NetCore3.1 配置Swagger
    1.nuget引入Swashbuckle.AspNetCore<ItemGroup><PackageReferenceInclude="Swashbuckle.AspNetCore"Version="6.4.0"/></ItemGroup>2.添加配置中间件Star......
  • netcore3.1升级到netcore6.0那些事儿
    netcore3.1升级到netcore6.0那些事儿netcore3.1升级到netcore6记录1:对于已存在的数据库,可以新建一个新版本控制台先用【DbFirst】的方式,生成数据库的dbcontext......
  • .net 温故知新:【10】.NET ORM框架EFCore使用入门之CodeFirs、DBFirst
    前言:本系列是我自己学习.net相关知识,以便跟上.net跨平台的步伐,目前工作原因基本在.netFramework4.7以下,所以才有了这一系列的学习总结,但是并不是从基本的C#语法和基础知识......
  • EFCore DBFirst从数据库生成实体类
    目录EFCoreDBFirst从数据库生成实体类官网安装指定NuGet包生成实体类EFCoreDBFirst从数据库生成实体类本示例仅适用于mysql版本,其他版本请根据官网说明进行操作。官网......
  • .netcore3.1使用log4net/nlog记录日志
    //.netcore使用log4net替换ILooger实现services.AddLogging(logBuilder=>{logBuilder.ClearProviders();log......