EF Core MYSQL 生成表映射配置问题

时间:2022-12-14 02:04:16

Model表

    public class Goods
{ public string ID { get; set; } public string CreatedBy { get; set; }
public DateTime CreatedTime { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedTime { get; set; } public string GoodsName { get; set; }
public int GoodsNum { get; set; }
}

配置文件

   public class GoodsEntityTypeConfiguration : IEntityTypeConfiguration<Goods>
{
public void Configure(EntityTypeBuilder<Goods> builder)
{
builder.ToTable("Sample_Goods_01"); builder.HasKey(ci => ci.ID); builder.Property(ci => ci.ID).IsRequired(); builder.Property(cb => cb.CreatedBy)
.IsRequired()
.HasMaxLength(20);
builder.Property(cb => cb.CreatedTime)
.IsRequired(); builder.Property(cb => cb.ModifiedBy)
.IsRequired()
.HasMaxLength(20); builder.Property(cb => cb.GoodsName)
.IsRequired(); builder.Property(cb => cb.GoodsNum)
.IsRequired();
}
}

EF Core MYSQL 生成表映射配置问题

在MYSQL里,想生成ID保存GUID,开始的时候直接生成 string 生成 text

没有达到我们的效果。ID应该为char(36),CreatedBy 应该为 varchar(20)

应该改为

   public class GoodsEntityTypeConfiguration : IEntityTypeConfiguration<Goods>
{
public void Configure(EntityTypeBuilder<Goods> builder)
{
builder.ToTable("Sample_Goods_01"); builder.Property(ci => ci.ID).IsRequired().HasMaxLength(36).HasColumnType("char(36)"); builder.Property(cb => cb.CreatedBy)
.IsRequired()
.HasMaxLength(20).HasColumnType("varchar(20)"); builder.Property(cb => cb.CreatedTime)
.IsRequired(); builder.Property(cb => cb.ModifiedBy)
.IsRequired()
.HasMaxLength(20).HasColumnType("varchar(20)"); builder.Property(cb => cb.GoodsName)
.IsRequired().HasColumnType("varchar(20)"); builder.Property(cb => cb.GoodsNum)
.IsRequired();
}
}

EF Core MYSQL 生成表映射配置问题

参考:

Jeffcky,EntityFramework Core映射关系详解

MVC - 10.CodeFrist

蝌蝌,EF6(CodeFirst)+MySql开发脱坑指南