EFCore连接PostgreSql

发布时间 2023-04-02 13:49:06作者: 关心千九

1、PostgreSql安装(windows安装)

  1.1、下载  

    下载地址:https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

    如下图,选择windows版本的安装包下载

  

   1.2、安装

    直接双击安装,期间会让你选择安装路径,数据存储路径,默认密码,端口等信息,可以按照需求填写,也可以直接使用默认地址安装。

    注意:默认密码一定要记住,第一次连接的时候会要求修改,默认端口5432,一般不用修改

2、使用EF连接pgsql

  2.1、使用vs新建一个项目,这里使用winform作为例子

  2.2、通过nuget引入Npgsql.EntityFrameworkCore.PostgreSQL

  

   2.3、创建MyDbContext

using Microsoft.EntityFrameworkCore;
using ProcessProperty.Entity;

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

        }

        /// <summary>
        /// Version表
        /// </summary>
        public DbSet<VersionEntity> VersionEntity { get; set; }
    }
}

  2.4、使用注入的方式注入MyDbContext(包括了其他service的注入)

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ProcessProperty.service;

namespace ProcessProperty
{
    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.UseNpgsql(config.GetConnectionString("PGSqlConnectionString"))
                );
            //先用DI容器生成 serviceProvider, 然后通过 serviceProvider 获取Main Form的注册实例
            var serviceProvider = services.BuildServiceProvider();
            //主动从容器中获取FormMain实例, 这是简洁写法
            var formMain = serviceProvider.GetRequiredService<Form1>();
            Application.Run(formMain);
        }

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

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

    appsetting.json

{
  "ConnectionStrings": {
    "PGSqlConnectionString": "server=localhost;port=5432;user id=postgres;password=postgres;database=app-version"
  }
}

  2.5、创建相应的Entity实体(数据表)

    主意:创建完成之后,要将其加入到MyDbContext

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProcessProperty.Entity
{
    [Table("version")]
    public class VersionEntity
    {
        [Column("id")]
        public Guid Id { get; set; }
        [Column("name")]
        public string? Name { get; set; }
    }
}

  2.6、使用

    使用构造函数注入方式注入,然后就按照正常的方式可以进行curl操作

public MyDbContext _myDbContext;

public ProcessDataService(MyDbContext myDbContext)
    {
        _myDbContext = myDbContext;
    }