Entity Framework Core中对实体类的字段迁移到数据库表

环境:NET Core 7.0   |  Entity Framework Core 7.0.10   |  Sql Server 数据库

1、创建解决方案  migration

2、创建类库 test.Domain

  引用包:

  Microsoft.EntityFrameworkCore.Abstractions

  创建类 AppUser.cs

using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace test.Domain
{
    [Comment("用户信息表")]
    public class AppUser
    {
        /// <summary>
        /// 主键,自增行为
        /// </summary>
        [Key]
        [Required]
        public long Id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        [MaxLength(64),Comment("姓名")]
        public string? Name1 { get; set; }
        /// <summary>
        /// 身份证
        /// </summary>
        [MaxLength(18), Comment("身份证")]
        public string IdNumber { get; set; }
        /// <summary>
        /// 性别男:1,女:2
        /// </summary>
        [Comment("性别男:1,女:2")]
        public int Gender { get; set; }
        /// <summary>
        /// 出生日期
        /// </summary>
        [Comment("出生日期")]
        public DateTime? Birthdate { get; set; }       



    }
}

  

| 特性名 | 说明 | 示例 | |---|---|---|
| [Key] | 如果是自增ID, 只需将主键属性声明为 int 或 long 类型,并加上 [Key] 特性(或命名为 Id,EF Core 会自动识别。 | [Key] public int Id { get; set; } | 
| [Required] | 指定属性为必填(非空),对应数据库的 NOT NULL。对于引用类型,不加问号即可达到同样效果。 | [Required] public string Name { get; set; } |
| [MaxLength(n)] | 指定字符串或数组的最大长度,映射为数据库字段长度。 | [MaxLength(128)] public string Name { get; set; } | 
| [MinLength(n)] | 指定字符串或数组的最小长度,仅用于模型验证,不影响数据库结构。 | [MinLength(2)] public string Name { get; set; } | 
| [StringLength(n)] | 同时指定最大长度和可选的最小长度,主要用于模型验证。 | [StringLength(100, MinimumLength = 10)] | 
| [Comment("备注")] | 指定数据库字段的备注(说明),EF Core 7+ 支持。 | [Comment("用户姓名")] | 
| [ConcurrencyCheck] | 标记属性为并发检查字段。 | [ConcurrencyCheck] public int Version { get; set; } | 
| [Timestamp] | 用于乐观并发控制,通常用于 byte[] 类型的时间戳。 | [Timestamp] public byte[] RowVersion { get; set; } | 
| [DatabaseGenerated(DatabaseGeneratedOption.Identity)] | 指定属性值由数据库生成(如自增主键)。 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] | 
| [DatabaseGenerated(DatabaseGeneratedOption.Computed)] | 指定属性为数据库计算列。 | [DatabaseGenerated(DatabaseGeneratedOption.Computed)] | 
| [ForeignKey("外键属性名")] | 指定外键属性。 | [ForeignKey("UserId")] | 
| [InverseProperty("属性名")] | 指定导航属性的反向关系。 | [InverseProperty("Orders")] | 
| [NotMapped] | 指定属性不映射到数据库表字段。 | [NotMapped] public string Temp { get; set; } | 
| [Column("列名")] | 指定数据库中的列名。 | [Column("user_name")] | 
| [Table("表名")] | 指定数据库中的表名(用于类)。 | [Table("Users")] | 
| [Index] | 指定索引(EF Core 5+ 支持,推荐用 Fluent API)。 | [Index(nameof(Name))] |

 

3、创建类库 test.EntityFrameworkCore

  引用包:

  Microsoft.EntityFrameworkCore.SqlServer

  Microsoft.EntityFrameworkCore.Design

  引用类库项目:

   test.Domain

  创建类 MealDbContext.cs

  

using test.Domain;
using Microsoft.EntityFrameworkCore;

namespace test.EntityFrameworkCore
{
    public class MealDbContext : DbContext
    {
        public MealDbContext(DbContextOptions<MealDbContext> options) : base(options)
        {
        }
        public virtual DbSet<AppUser> AppUsers { get; set; }

        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {            
            //modelBuilder.Entity<AppUser>(b =>
            //{
            //    //Indexes
            //    b.HasKey(x => x.Id).IsClustered(false);
            //});

            
        }
    }
}

  创建类 DesignTimeDbContextFactory.cs

using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;

namespace test.EntityFrameworkCore
{
    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MealDbContext>
    {
        public DesignTimeDbContextFactory()
        {
        }

        public MealDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MealDbContext>();
            optionsBuilder.UseSqlServer("Server=127.0.0.1;Database=MealDb;User Id=sa;Password=123456;Encrypt=False;");

            return new MealDbContext(optionsBuilder.Options);
        }
    }
}

4、迁移命令:

  打开终端 执行命令:

  //添加migrations的up_appUser    ,up_appUser是迁移名称,可自定义。

  D:\migration\test.EntityFrameworkCore>dotnet ef migrations add up_appUser

  //同步到数据库

  D:\migration\test.EntityFrameworkCore>dotnet ef database update

5、常见问题:

  • 如果有多个 DbContext,可用 -Context 参数指定。
  • 迁移文件会生成在项目的 Migrations 文件夹下。
  • 修改实体后,重复执行 dotnet ef migrations add xxx 和 dotnet ef database update 即可同步结构。

  • 删除最新的migrations: dotnet ef migrations remove