EntityFrameCore CodeFirst 迁移

devtools/2025/2/26 12:17:07/

CodeFirst 代码先行,只关心业务,需要什么对象就写什么对象;

Nuget引入程序集

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools

生成迁移文件

命令: add-migration Init001      添加迁移文件

            update-database            根据最新的迁移文件生成数据库

 

 更新数据库

Commodity

    public partial class Commodity{public int Id { get; set; }public long? ProductId { get; set; }public int? CategoryId { get; set; }public string? Title { get; set; }public decimal? Price { get; set; }public string? Url { get; set; }public string? ImageUrl { get; set; }}

CompanyInfo

public partial class CompanyInfo
{public CompanyInfo(){SysUsers = new HashSet<SysUser>();}public int Id { get; set; }public string? CompanyName { get; set; }public DateTime? CreateTime { get; set; }public int CreatorId { get; set; }public int? LastModifierId { get; set; }public DateTime? LastModifyTime { get; set; }public virtual ICollection<SysUser> SysUsers { get; set; }
}

SysUser

public partial class SysUser
{public int Id { get; set; }public string? Name { get; set; }public string? Password { get; set; }public int Status { get; set; }public string? Phone { get; set; }public string? Mobile { get; set; }public string? Address { get; set; }public string? Email { get; set; }public long? Qq { get; set; }public string? WeChat { get; set; }public int? Sex { get; set; }public DateTime? LastLoginTime { get; set; }public DateTime? CreateTime { get; set; }public int? CreateId { get; set; }public DateTime? LastModifyTime { get; set; }public int? LastModifyId { get; set; }public int? CompanyId { get; set; }public virtual CompanyInfo? Company { get; set; }
}

CustomerDbContext

    public partial class CustomerDbContext : DbContext{public CustomerDbContext(){}public CustomerDbContext(DbContextOptions<CustomerDbContext> options): base(options){}public virtual DbSet<Commodity> Commodities { get; set; } = null!;public virtual DbSet<CompanyInfo> CompanyInfo { get; set; } = null!;public virtual DbSet<SysUser> SysUsers { get; set; } = null!;protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){if (!optionsBuilder.IsConfigured){
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=LearnCustomerDB_New;User ID=sa;Password=123456");}}protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.Entity<Commodity>(entity =>{entity.ToTable("Commodity");entity.Property(e => e.ImageUrl).HasMaxLength(1000).IsUnicode(false);entity.Property(e => e.Price).HasColumnType("decimal(18, 2)");entity.Property(e => e.Title).HasMaxLength(500).IsUnicode(false);entity.Property(e => e.Url).HasMaxLength(1000).IsUnicode(false);});modelBuilder.Entity<CompanyInfo>(entity =>{entity.ToTable("Company");entity.Property(e => e.CreateTime).HasColumnType("datetime");entity.Property(e => e.LastModifyTime).HasColumnType("datetime");entity.Property(e => e.CompanyName).HasMaxLength(50).IsUnicode(false);});modelBuilder.Entity<SysUser>(entity =>{entity.ToTable("SysUser");entity.Property(e => e.Address).HasMaxLength(500).IsUnicode(false);entity.Property(e => e.CreateTime).HasColumnType("datetime");entity.Property(e => e.Email).HasMaxLength(50).IsUnicode(false);entity.Property(e => e.LastLoginTime).HasColumnType("datetime");entity.Property(e => e.LastModifyTime).HasColumnType("datetime");entity.Property(e => e.Mobile).HasMaxLength(12).IsUnicode(false);entity.Property(e => e.Name).HasMaxLength(50).IsUnicode(false);entity.Property(e => e.Password).HasMaxLength(50).IsUnicode(false);entity.Property(e => e.Phone).HasMaxLength(12).IsUnicode(false);entity.Property(e => e.Qq).HasColumnName("QQ");entity.Property(e => e.WeChat).HasMaxLength(50).IsUnicode(false);entity.HasOne(d => d.Company).WithMany(p => p.SysUsers).HasForeignKey(d => d.CompanyId).OnDelete(DeleteBehavior.Cascade).HasConstraintName("FK_SysUser_CompanyInfo");});OnModelCreatingPartial(modelBuilder);}partial void OnModelCreatingPartial(ModelBuilder modelBuilder);}

EFCoreCodeFirst

    public class EFCoreCodeFirst{public static void Show(){using (CustomerDbContext context = new CustomerDbContext()){context.Database.EnsureDeleted(); //删除数据库context.Database.EnsureCreated();//创建全新的数据库 }}}

Program.cs

// See https://aka.ms/new-console-template for more information
using Learn.NET6.DemoTest;Console.WriteLine("Hello, World!");//EFCoreDbFirst.Show();EFCoreCodeFirst.Show();

补充:EntityFrameCore6.0-LinqToSql

public class EFQueryTest
{public static void Show(){#region 其他查询using (CustomerDbContext dbContext = new CustomerDbContext()){{var ids = new int[] { 54, 55, 56, 57, 58, 59, 60, 61, 63 };var list = dbContext.SysUsers.Where(u => 1 == 1 && !(ids.Contains(u.Id)));//in查询foreach (var user in list){Console.WriteLine(user.Name);}}{var list = from u in dbContext.SysUserswhere new int[] { 54, 55, 56, 57, 58, 59, 60, 61, 63 }.Contains(u.Id)select u;foreach (var user in list){Console.WriteLine(user.Name);}}{var list = dbContext.SysUsers.Where(u => new int[] { 54, 55, 56, 57, 58, 59, 60, 61, 63 }.Contains(u.Id)).OrderBy(u => u.Id) //排序--升序.OrderByDescending(c => c.Name).Select(u => new //投影{Name = u.Name,Pwd = u.Password}).Skip(3).Take(5); //跳过三条  再获取5条foreach (var user in list){Console.WriteLine(user.Name);}}{var list = dbContext.SysUsers.Where(u => u.Name.StartsWith("Richard") && u.Name.EndsWith("小王子")).Where(u => u.Name.EndsWith("小王子")).Where(u => u.Name.Contains("小王子")).Where(u => u.Name.Length < 10).OrderBy(u => u.Id);foreach (var user in list){Console.WriteLine(user.Name);}}{var list = from u in dbContext.CompanyInfojoin c in dbContext.SysUsers on u.Id equals c.CompanyIdwhere new int[] { 1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17 }.Contains(u.Id)select new{Name = u.CompanyName,UserName = c.Name,Address = c.Address};foreach (var user in list){System.Console.WriteLine($"{user.Name}-{user.Address}");}}}using (CustomerDbContext dbContext = new CustomerDbContext()){{try{string sql = "Update dbo.SysUser Set Password='小王子' WHERE Id=@Id";SqlParameter parameter = new SqlParameter("@Id", 1);int flag = dbContext.Database.ExecuteSqlRaw(sql, parameter);}catch (Exception ex){throw ex;}}}using (CustomerDbContext dbContext = new CustomerDbContext()){{IDbContextTransaction trans = null;try{trans = dbContext.Database.BeginTransaction();string sql = "Update dbo.SysUser Set Password='Test00xx' WHERE Id=@Id";SqlParameter parameter = new SqlParameter("@Id", 3843);dbContext.Database.ExecuteSqlRaw(sql, parameter);string sql1 = "Update dbo.SysUser Set Password='Test00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abcTest00abc' WHERE Id=@Id";SqlParameter parameter1 = new SqlParameter("@Id", 3843);dbContext.Database.ExecuteSqlRaw(sql1, parameter1);trans.Commit();}catch (Exception ex){if (trans != null)trans.Rollback();}finally{trans.Dispose();}}}#endregion}
}


http://www.ppmy.cn/devtools/162782.html

相关文章

kafka队列堆积的常见解决

1. 检查生产者是否正常工作 如果生产者速度太慢或者不稳定&#xff0c;可以通过增加生产者吞吐量来解决。 解决方案&#xff1a; 提高生产者的吞吐量&#xff1a;可以通过调整生产者配置来增加吞吐量。 设置生产者 acks 参数为 1 或 0&#xff08;如果不需要严格的消息确认&…

uniapp小程序自定义日历(签到、补签功能)

1、切换月份根据当前月判断&#xff0c;只能切换当前月份之前的时间。 2、补卡功能&#xff0c;根据后台设置自己写上即可&#xff0c;可补签多少天。 3、点击签到是签到当前天的&#xff0c;不能指定签到时间。 备注&#xff1a;当前代码只构建了排版样式和切换月份功能&…

RAG技术落地:核心痛点与应对策略全面解析

RAG技术落地&#xff1a;核心痛点与应对策略全面解析 RAG技术落地&#xff1a;核心痛点与应对策略全面解析一、技术实现层的四大挑战二、数据质量管理的生死线三、产业落地的软性痛点四、未来技术演进方向 RAG技术落地&#xff1a;核心痛点与应对策略全面解析 检索增强生成&a…

UE(虚幻)学习(五)初学创建NPC移动和遇到的问题

最近在学习UE中遇到一些问题&#xff0c;把这些问题记录一下&#xff0c;因为实在废了很大功夫。 在学习了UE5的例子中的第三人称移动Demo&#xff0c;想实现几个NPC在场景内移动。 本来想自己写一个类&#xff0c;遇到一堆问题花费了好几天时间&#xff0c;所以我把问题写下来…

【qt计算器】

qt计算器 目录注释部分模块配置目标配置模板配置源文件配置头文件配置UI 文件配置1. 头文件保护宏2. 包含必要的头文件3. 命名空间声明4. 类的定义5. 构造函数和析构函数6. 私有槽函数7. 私有成员变量8. 头文件保护宏结束1. 包含头文件2. 构造函数 MainWindow::MainWindow(QWid…

使用机器学习进行土地覆盖分类

土地利用和土地覆盖 (LULC) 分类在林业和农业领域发挥着重要作用&#xff0c;无论是种植园管理、生态系统恢复、碳市场计划还是其他应用。监测土地覆盖和土地利用变化是特许权所有者的一项强制性任务&#xff0c;需要对其特许权区域进行一致且准确的分析。 作为一名 GIS 分析师…

数据结构——排序2

今天&#xff0c;我们来讲解一下选择排序和冒泡排序还有堆排序。 选择排序的基本思想&#xff1a;每一次从待排序的数据元素中选出最小&#xff08;或最大&#xff09;的一个元素&#xff0c;存放在序列的起始位置&#xff0c;直到全部待排序的数据元素排完 。 下图中只选取了它…

显卡(Graphics Processing Unit,GPU)架构详细解读

显卡架构主要分为两大类&#xff1a;GPU 核心架构&#xff08;也称为图形处理单元架构&#xff09;和显卡的其他组件&#xff08;如内存、控制器、输出接口等&#xff09;。本篇文章将对显卡架构进行详细分析&#xff0c;重点介绍 GPU 核心架构、显卡计算单元、显存结构、显卡管…