在.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