.NET 8 WinForms 使用 PostgreSQL + LINQ 實例教學
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1145
如果你正在啟用 .NET 8 WinForms 對 PostgreSQL 執行 LINQ 操作,這篇簡明教學就是為你擾備的。
ᵀ. 安裝 NuGet 套件
打開 NuGet 套件管理器,執行:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
ᵁ. 建立 DbContext
新增 BKDbContext.cs
:
using Microsoft.EntityFrameworkCore;
using BKSystem.Tbl;
namespace BKSystem.Data;
public class BKDbContext : DbContext
{
public DbSet<Kobetu> Kobetus { get; set; } = null!;
public DbSet<Kanribo> Kanribos { get; set; } = null!;
public DbSet<UkeharaiMeisai> UkeharaiMeisais { get; set; } = null!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=localhost;Database=mydb;Username=myuser;Password=mypass");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UkeharaiMeisai>().HasKey(x => new { x.DocCd, x.MeisaiNo });
modelBuilder.Entity<Kobetu>().ToTable("kobetu_tbl");
modelBuilder.Entity<Kanribo>().ToTable("kanribo_tbl");
modelBuilder.Entity<UkeharaiMeisai>().ToTable("ukeharai_meisai_tbl");
}
}
ᵂ. WinForms 使用 LINQ 操作 PostgreSQL
在按鈕事件中操作:
using BKSystem.Data;
private void btnLoad_Click(object sender, EventArgs e)
{
using var db = new BKDbContext();
var list = db.Kobetus.Where(k => k.KanrikanCd == "A01").OrderBy(k => k.ShutokuYmd).ToList();
MessageBox.Show($"數量: {list.Count}");
}
ᵃ. 記住
-
DbContext
不能共用,每次操作都要new
一次 -
EF Core 會追蹤資料狀態,請勿使用長久存在的封裝
-
PostgreSQL 有大小寫效感,建議
.HasColumnName("xxx")
明確映射
結論
WinForms 也能使用 LINQ 進行 PostgreSQL 操作,通過 Entity Framework Core 和 Npgsql 套件即可達成。操作平易,管理效率高。
This article was last edited at