1. 程式人生 > 其它 >ef core 資料遷移

ef core 資料遷移

1 安裝EF Core 命令列工具

安裝命令

dotnet tool install --global dotnet-ef

2 搭建好專案 entity,map,dbContext

在專案中新增如下引用:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Relational

Microsoft.EntityFrameworkCore.SqlServer

3.1 新增 entities

SysUserEntity 如下

namespace ConsoleApp_EFMigration.Entities
{
    
public class SysUserEntity { /// <summary> /// Id /// </summary> public string Id { get; set; } /// <summary> /// 使用者賬號 /// </summary> public string UserCode { get; set; } /// <summary> /// 使用者名稱 /// </summary>
public string UserName { get; set; } } }

3.2 新增 maps

SysUserMap 如下

using ConsoleApp_EFMigration.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ConsoleApp_EFMigration.Maps
{
    public class SysUserMap : IEntityTypeConfiguration<SysUserEntity>
    {
        
public void Configure(EntityTypeBuilder<SysUserEntity> builder) { builder.ToTable("SysUser"); // 對映到表 SysUser builder.HasKey(c => c.Id); // 表 主鍵為 Id } } }

3.3 新增 dbContexts

資料庫 Test 的上下文類如下

using ConsoleApp_EFMigration.Entities;
using ConsoleApp_EFMigration.Maps;
using Microsoft.EntityFrameworkCore;

namespace ConsoleApp_EFMigration.DbContexts
{
    /// <summary>
    /// 資料庫 Test 上下文類
    /// </summary>
    public class TestDbContext : DbContext
    {
        public TestDbContext()
        {
            Database.EnsureCreated();
        }

        public DbSet<SysUserEntity> SysUsers { get; set; }
        public DbSet<SysRoleEntity> SysRoles { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new SysUserMap());
            modelBuilder.ApplyConfiguration(new SysRoleMap());

            base.OnModelCreating(modelBuilder);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            string connStr = "Server=****;Database=Test;Uid=sa;Pwd=****;TrustServerCertificate=True;";
            optionsBuilder.UseSqlServer(connStr); // SqlServer 資料庫
        }
    }
}

3 在專案.csproj檔案目錄下,檔案位址列輸入 cmd

4新增遷移

在 cmd 視窗中輸入新增遷移命令如下:

dotnet ef migrations add First

// 撤銷遷移 dotnet ef migrations add AddProvinceName2 命令

dotnet ef migrations remove

5 應用遷移

在cmd視窗中執行以下遷移命令

dotnet ef database update

6 檢視遷移結果

參考連結

https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli

https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli