《Asp.Net Core3 + Vue3入坑教程》 – 4.EF Core & Postgresql
- 2021 年 3 月 2 日
- 筆記
- .NET, ef core, PostgreSQL
簡介
《Asp.Net Core3 + Vue3入坑教程》 此教程適合新手入門或者前後端分離嘗試者。可以根據圖文一步一步進操作編碼也可以選擇直接查看源碼。每一篇文章都有對應的源碼
教程後期會將 .Net Core 3升級成 .Net Core 5
目錄
《Asp.Net Core3 + Vue3入坑教程》系列教程目錄
Asp.Net Core後端項目
- 後端項目搭建與Swagger配置步驟
- 配置CROS策略解決跨域問題
- AutoMapper & Restful API & DI
- (本文)EF Core & Postgresql
- (暫未發表敬請期待…).Net Core 3升級成 .Net Core 5
- (暫未發表敬請期待…)JWT
Vue3 前端項目
暫未發表敬請期待…
本文簡介
本文為《Asp.Net Core3 + Vue3入坑教程》系列教程的後端第四篇 – EF Core & Postgresql。上文已經為Simple項目增加了Restful API 但是數據是模擬出來的,本文繼續為Simple項目增加與Postgresql資料庫的連接,並使用EF Core ORM框架實現與資料庫的交互。
EF Core & Postgresql
安裝postgresql資料庫
直接進官網下載 //www.postgresql.org/
安裝完成後,找到安裝目錄啟動psql.exe
安裝 navicat
也可以不安裝navicat,使用其他資料庫客戶端
運行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 //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) 組成。更多內容參考 //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命令,具體可以參考 //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的內容很多本文只有簡單的使用,更多知識可以參考 //docs.microsoft.com/en-us/ef/core/ 文檔進行深入學習!
GitHub源碼
注意:源碼調試過程中如果出現xml文件路徑錯誤,需要參照第一章(後端項目搭建與Swagger配置步驟)Swagger配置「配置XML 文檔文件」步驟,取消勾選然後再選中 ,將XML路徑設置成與你的電腦路徑匹配!
//github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 4.EF Core %26 Postgresql
參考資料
EF Core官網文檔(推薦學習) //docs.microsoft.com/en-us/ef/core/
.Net Core CLI命令 //docs.microsoft.com/zh-cn/dotnet/core/tools/
微軟官方文檔 //docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-5.0