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.'
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

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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With