Json 列的 EF Core 数据播种

问题描述 投票:0回答:1

我正在尝试在具有一些 json 列的 EF core DbContext 中添加数据种子。

public class MapPoint
{
    public Guid Id { get; set; }
    public Location Location { get; set; }
}
public class Location
{
    public int x { get; set; }
    public int y { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}

我在数据库上下文 OnModelCreating 中添加了数据种子,当我想要添加迁移时,我收到此错误: 无法创建类型为“”的“DbContext”。异常“无法将 HasData 用于实体类型“MapPoint”。映射到 JSON 的实体不支持 HasData。'

c# entity-framework asp.net-core entity-framework-core
1个回答
0
投票

正如错误所述,Json 列不支持 HasData。
您可以尝试使用模型构建器约定来定义“将数据保存到数据库”/“从数据库获取值”时的表达式,以便配置具有完整播种功能的“json 字段”。
对于您的实体,您可以像下面这样配置 DbContext:

    public class MyContext :DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=10.96.5.5;Initial Catalog=wp44;User ID=sa;Password=xxxxx;TrustServerCertificate=True");
        }

        public DbSet<MapPoint> MapPoints { get; set; }

  
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<MapPoint>().Property(b => b.Location)
                .HasConversion(
                    v => JsonConvert.SerializeObject(v),
                    v => JsonConvert.DeserializeObject<Location>(v));


            modelBuilder.Entity<MapPoint>().HasData(new MapPoint { Id=Guid.NewGuid(),  Location=new Location { x=1} });
        }  
    }

迁移更新后的结果

然后你可以像下面一样使用上下文:

//Add value
_context.MapPoints. Add(new MapPoint { Id = Guid.NewGuid(), Location = new Location { x = 2 }});
//Get value
MapPoint value = _context.MapPoints.FirstOrDefault();
© www.soinside.com 2019 - 2024. All rights reserved.