在.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 static readonly string ConnStr = ConfigurationManager.ConnectionStrings["MysqlContext"] + "";
        public static ServerVersion? SerVersion = null;
        public ServerVersion GetServerVersion()
        {
            if (SerVersion == null)
            {
                SerVersion = ServerVersion.AutoDetect(ConnStr);
            }
            return SerVersion;
        }
        #region DbSet
        public DbSet<Student> Students { get; set; }
        #endregion
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //连接mysql,需要安装 Pomelo.EntityFrameworkCore.MySql
            //string connStr = ConfigurationManager.ConnectionStrings["MysqlContext"] + "";
            //var serVersion = ServerVersion.AutoDetect(ConnStr);
            //optionsBuilder.UseMySql(connStr, serverVersion);
            
            //上面的方式在频繁操作数据库的时候报错
            optionsBuilder.UseMySql(ConnStr, GetServerVersion());

            //连接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

添加一个配置文件app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="Setting1" value="Value1" />
    </appSettings>
    <connectionStrings>
        <add name="MysqlContext" connectionString="server=localhost;port=3306;database=xcgdb;uid=root;pwd=root;charset=utf8mb4;"/>
    </connectionStrings>
</configuration>

 

posted on 2024-05-21 11:52  邢帅杰  阅读(773)  评论(0编辑  收藏  举报