.net8 winform程式使用EntityFrameworkCore連線資料庫

邢帅杰發表於2024-05-21

在.NET 8 WinForms應用程式中使用Entity Framework (EF) Core,你需要按照以下步驟操作:
1.新增Entity Framework Core NuGet包。
2.定義你的資料模型。
3.建立資料庫上下文 (DbContext)。
4.在資料庫上下文中配置Entity Framework。
5.使用Entity Framework Core的API來執行資料庫操作。
以下是一個簡單的示例:

安裝Entity Framework Core NuGet包:
連線sqlserver資料庫
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

連線Mysql資料庫
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore.Tools

定義資料模型:

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace WinFormsApp.Models
{
    [Table("student")]
    public class Student
    {
        /// <summary>
        /// 主鍵,自增
        /// </summary>
        [Key, Column("id"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [Column("last_name"), StringLength(50)]
        public string LastName { get; set; } = string.Empty;
        [Column("first_mid_name"),StringLength(50)]
        public string FirstMidName { get; set; } = string.Empty;
        [Column("enrollment_date")]
        public DateTime EnrollmentDate { get; set; }
    }
}

建立資料庫上下文:

using System.Configuration;
using Microsoft.EntityFrameworkCore;
using WinFormsApp.Models;

namespace WinFormsApp
{
    public class XCGDbContext : DbContext
    {
        public DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //連線mysql,需要安裝 Pomelo.EntityFrameworkCore.MySql
            string connStr = ConfigurationManager.ConnectionStrings["MysqlContext"] + "";
            var serverVersion = ServerVersion.AutoDetect(connStr);
            optionsBuilder.UseMySql(connStr, serverVersion);

            //連線sql,需要安裝 Microsoft.EntityFrameworkCore.SqlServer
            //optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True");
        }
    }
}

在winform程式中使用EF Core:

using (var context = new XCGDbContext())
{
    // 新增
    context.Students.Add(new Student { EnrollmentDate = DateTime.Now, FirstMidName = "jay" + DateTime.Now.Ticks, LastName = "x" });
    context.SaveChanges();

    // 查詢
    var stus = context.Students.ToList();

    // 更新
    foreach (var stu in stus)
    {
        stu.LastName = "star";
    }
    context.SaveChanges();

    // 刪除
    var stuToDelete = context.Students.FirstOrDefault();
    context.Students.Remove(stuToDelete);
    context.SaveChanges();
}

使用以下命令來建立和應用資料庫遷移:
dotnet ef migrations add InitialCreate
dotnet ef database update

相關文章