《Asp.Net Core3 + Vue3入坑教程》 - 4.EF Core & Postgresql


簡介

《Asp.Net Core3 + Vue3入坑教程》 此教程適合新手入門或者前后端分離嘗試者。可以根據圖文一步一步進操作編碼也可以選擇直接查看源碼。每一篇文章都有對應的源碼

教程后期會將 .Net Core 3升級成 .Net Core 5

目錄

《Asp.Net Core3 + Vue3入坑教程》系列教程目錄

Asp.Net Core后端項目

  1. 后端項目搭建與Swagger配置步驟
  2. 配置CROS策略解決跨域問題
  3. AutoMapper & Restful API & DI
  4. (本文)EF Core & Postgresql
  5. (暫未發表敬請期待...).Net Core 3升級成 .Net Core 5
  6. (暫未發表敬請期待...)JWT

Vue3 前端項目

暫未發表敬請期待...

本文簡介

本文為《Asp.Net Core3 + Vue3入坑教程》系列教程的后端第四篇 - EF Core & Postgresql。上文已經為Simple項目增加了Restful API 但是數據是模擬出來的,本文繼續為Simple項目增加與Postgresql數據庫的連接,並使用EF Core ORM框架實現與數據庫的交互。

EF Core & Postgresql

安裝postgresql數據庫

直接進官網下載 https://www.postgresql.org/

安裝完成后,找到安裝目錄啟動psql.exe

安裝 navicat

也可以不安裝navicat,使用其他數據庫客戶端

官網下載 http://www.navicat.com.cn/

運行navicat 鏈接 postgresql 數據庫

連接配置如下,密碼123456

准備工作就緒,這時候回到項目中

安裝Microsoft.EntityFrameworkCore Nuget包

安裝Microsoft.EntityFrameworkCore.Design Nuget包

安裝Npgsql.EntityFrameworkCore.PostgreSQL Nuget包

增加Postgresql鏈接配置,調整Startup.cs

代碼如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using Simple_Asp.Net_Core.Data;
using Simple_Asp.Net_Core.ServiceProvider;
using System;

namespace Simple_Asp.Net_Core
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<CommanderContext>(options =>
                options.UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=123456"));

            services.AddCORS();
            services.AddMvc();
            services.AddSwagger();

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddScoped<ICommanderRepo, MockCommanderRepo>();

            services.AddControllers().AddNewtonsoftJson(s =>
            {
                s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
                });
            }

            app.UseCors("CorsTest");

            app.UseRouting();
            app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
        }
    }
}

在Data文件夾下新建類CommanderContext.cs

使用 EF Core 時,數據訪問是通過使用模型來執行的。 模型由(域模型)實體類和表示與數據庫的會話的派生上下文 (DbContext) 組成。更多內容參考 https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.entityframeworkcore.dbcontext?view=efcore-5.0

代碼如下

using Microsoft.EntityFrameworkCore;
using Simple_Asp.Net_Core.Models;

namespace Simple_Asp.Net_Core.Data
{
    public class CommanderContext : DbContext
    {
        public CommanderContext(DbContextOptions<CommanderContext> opt) : base(opt)
        {
        }

        public DbSet<Command> Commands { get; set; }
    }
}


實現 ICommanderRepo 倉儲層接口,在Data文件夾下新建類 SqlCommanderRepo.cs

using Simple_Asp.Net_Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Simple_Asp.Net_Core.Data
{
    public class SqlCommanderRepo : ICommanderRepo
    {
        private readonly CommanderContext _context;

        public SqlCommanderRepo(CommanderContext context)
        {
            _context = context;
        }

        public void CreateCommand(Command cmd)
        {
            if (cmd == null)
            {
                throw new ArgumentNullException(nameof(cmd));
            }

            _context.Commands.Add(cmd);
        }

        public void DeleteCommand(Command cmd)
        {
            if (cmd == null)
            {
                throw new ArgumentNullException(nameof(cmd));
            }
            _context.Commands.Remove(cmd);
        }

        public IEnumerable<Command> GetAllCommands()
        {
            return _context.Commands.ToList();
        }

        public Command GetCommandById(int id)
        {
            return _context.Commands.FirstOrDefault(p => p.Id == id);
        }

        public bool SaveChanges()
        {
            return (_context.SaveChanges() >= 0);
        }

        public void UpdateCommand(Command cmd)
        {
            //Nothing
        }
    }
}

再次調整 Startup.cs ,將ICommanderRepo 接口實現替換成SqlCommanderRepo

services.AddScoped<ICommanderRepo, MockCommanderRepo>();
    =>
services.AddScoped<ICommanderRepo, SqlCommanderRepo>();

使用swagger進行調試,調用/api/Commands接口

因為數據庫中缺少Commands表,所以后端報錯了,接下來我們使用EF自動創建Commands表

打開開發者命令提示窗口

接下來會使用到 .Net Core CLI命令,具體可以參考 https://docs.microsoft.com/zh-cn/dotnet/core/tools/

將EF注冊成全局工具

命令如下:

dotnet tool install --global dotnet-ef

執行遷移初始化命令

命令如下:

dotnet ef migrations add InitialMigration

發現報錯了

因為當前文件夾找不到解決方案,所以報錯了

進入Simple_Asp.Net_Core文件夾再次執行遷移初始化命令

命令如下:

cd Simple_Asp.Net_Core

dotnet ef migrations add InitialMigration

執行成功

在項目中可以看到生成了Migrations文件夾

接下來使用EF將表的變化更新到Postgresql數據庫上

cd Simple_Asp.Net_Core

dotnet ef database update

打開navicat,可以發現增加了兩張表,一張是EF遷移歷史表,另一張就是Commands表

現在本章針對Simple項目的代碼編寫與EF配置工作已經完成!

現在我們可以使用swagger進行接口測試,並查看數據是否有正確保存與返回

總結

本文為Simple項目增加與Postgresql數據庫的連接,這里數據庫可以替換成其他數據庫,只需引入正確Nuget包,以及調整數據庫連接配置即可!本文應用的是EF Core里的Code First方式進行開發,EF Core的內容很多本文只有簡單的使用,更多知識可以參考 https://docs.microsoft.com/en-us/ef/core/ 文檔進行深入學習!

GitHub源碼

注意:源碼調試過程中如果出現xml文件路徑錯誤,需要參照第一章(后端項目搭建與Swagger配置步驟)Swagger配置“配置XML 文檔文件”步驟,取消勾選然后再選中 ,將XML路徑設置成與你的電腦路徑匹配!

https://github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 4.EF Core %26 Postgresql

參考資料

EF Core官網文檔(推薦學習) https://docs.microsoft.com/en-us/ef/core/

.Net Core CLI命令 https://docs.microsoft.com/zh-cn/dotnet/core/tools/

微軟官方文檔 https://docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-5.0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM