数据库
首页 > 数据库> > asp.core webapi连接postgresql数据库

asp.core webapi连接postgresql数据库

作者:互联网

1、如果库里已存在数据库

(1)、appsettings.json下添加连接字符串

  "ConnectionStrings": {
    "PostgreSql": "User ID=postgres;Password=xxx;Host=localhost;Port=5432;Database=xx"
  },

 

(1)、通过NuGet安装Entity Framework并更新文件project.json中“tools”区

Install-Package Npgsql.EntityFrameworkCore.PostgreSQL
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.Design
Install-Package Microsoft.EntityFrameworkCore.Tools -Pre

 

(2)、NuGet包管理器运行命令

Scaffold-DbContext “Server=localhost;Database=xx;User ID=postgres;Password=wantgirl;” Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models

 

(3)、已获取数据库表

 

 

 (4)、startup下注入连接字符串

 services.AddDbContext<chdocContext>(option => option.UseNpgsql(Configuration.GetConnectionString("PostgreSql")));
           

(5)、需要操作直接调用方法即可

 

 

 

2、如果表里没有库

(1)在Model文件夹下添加Todoitem类

using System;
using System.ComponentModel.DataAnnotations;
namespace TodoApi.Models
{
    public class TodoItem
    {
        /// <summary>
        /// 匹配编号
        /// </summary>
        [Key]
        public Guid Gid { get; set; }
        /// <summary>
        /// 上传文件名
        /// </summary>
        public string UploadFileName { get; set; }
        /// <summary>
        /// 上传文件路径
        /// </summary>
        public string UploadFilePath { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// 状态 0:匹配中  1:匹配完成未下载 2:匹配完成已下载
        /// </summary>
        public int Status { get; set; }
        /// <summary>
        /// 下载文件名
        /// </summary>
        public string DownloadFileName { get; set; }
        /// <summary>
        /// 下载文件路径
        /// </summary>
        public string DownloadFilePath { get; set; }
        /// <summary>
        /// 下载时间
        /// </summary>
        public DateTime? DownloadTime { get; set; }
        /// <summary>
        /// 下载次数
        /// </summary>
        public int DownLoadCount { get; set; }
    }
}

 

(2)、NuGet包管理器执行命令(也可以直接添加引用)

Install-Package Npgsql.EntityFrameworkCore.PostgreSQL
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.Design
Install-Package Microsoft.EntityFrameworkCore.Tools

 

(3)、将字符串写入appsetting.json

"ConnectionStrings": {
    "PostgreSql": "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=mydatabase"
  },

 

(4)、在Model文件夹下添加TodoContext类

using Microsoft.EntityFrameworkCore;
namespace TodoApi.Models{
    public class TodoContext :DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options):base(options){

        }
        public DbSet<TodoItem> TodoItems {get;set;}

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}

 

(5)修改startup

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(option => option.UseNpgsql(Configuration.GetConnectionString("PostgreSql")));
        } 

 

(6)、NuGet包管理器执行命令

Add-Migration TodoItem
Update-Database

(7)、添加控制器

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;
using System;
namespace TodoApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoController(TodoContext context)
        {
            _context = context;

            if (_context.TodoItems.Count() == 0)
            {
                // Create a new TodoItem if collection is empty,
                // which means you can't delete all TodoItems.
                _context.TodoItems.Add(new TodoItem { UploadFileName = "Item1" });
                _context.SaveChanges();
            }
        }
        [HttpGet]
        public ActionResult<List<TodoItem>> GetAll()
        {
            return _context.TodoItems.ToList();
        }

        [HttpGet("{gid}", Name = "GetTodo")]
        public ActionResult<TodoItem> GetById(Guid gid)
        {
            var item = _context.TodoItems.Find(gid);
            if (item == null)
            {
                return NotFound();
            }
            return item;
        }
    }
   
}

END

网址方法很多我也总结了下

参考博客

(23条消息) 全栈练习一:asp.net core 2.1 webapi连接postgrest数据库从零开始_henjuewang的博客-CSDN博客

ASP.NET Core 对接已存在的PostgreSQL数据库 | 春小麦 (firstsolver.com)

 

标签:webapi,core,asp,get,EntityFrameworkCore,set,context,using,public
来源: https://www.cnblogs.com/dongzi1997/p/16210865.html