How to store JSON in an entity field with EF Core?

前端 未结 10 485
死守一世寂寞
死守一世寂寞 2020-11-29 17:13

I am creating a reusable library using .NET Core (targeting .NETStandard 1.4) and I am using Entity Framework Core (and new to both). I have an entity class that looks like

10条回答
  •  遥遥无期
    2020-11-29 18:18

    Here's something I used

    Model

    public class FacilityModel 
    {
        public string Name { get; set; } 
        public JObject Values { get; set; } 
    }
    

    Entity

    [Table("facility", Schema = "public")]
    public class Facility 
    {
         public string Name { get; set; } 
         public Dictionary Values { get; set; } = new Dictionary();
    }
    

    Mapping

    this.CreateMap().ReverseMap();
    

    DBContext

    base.OnModelCreating(builder); 
            builder.Entity()
            .Property(b => b.Values)
            .HasColumnType("jsonb")
            .HasConversion(
            v => JsonConvert.SerializeObject(v),
            v => JsonConvert.DeserializeObject>(v));
    

提交回复
热议问题