Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core Data Seeding for Json column

I am trying to Data seed in EF core DbContext that has some json column.

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; }
}

I Added Data seed in Db context OnModelCreating and when I want to Add-Migration I get this error: Unable to create a 'DbContext' of type ''. The exception 'Can't use HasData for entity type 'MapPoint'. HasData is not supported for entities mapped to JSON.'

like image 449
mahdi Avatar asked Dec 07 '25 16:12

mahdi


1 Answers

As the error said, Json column doesn't support HasData.
You could try use modelbuilder convention to define the expression when "save data to database" / "get value from database" in order to configure a "json field" with full seeding function.
With your entities, you could configure DbContext like following:

    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} });
        }  
    }

Result after migration and update
enter image description here

Then you could use the context just like below:

//Add value
_context.MapPoints. Add(new MapPoint { Id = Guid.NewGuid(), Location = new Location { x = 2 }});
//Get value
MapPoint value = _context.MapPoints.FirstOrDefault();
like image 194
Jerry Fu Avatar answered Dec 09 '25 17:12

Jerry Fu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!