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

前端 未结 10 486
死守一世寂寞
死守一世寂寞 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 17:57

    @Michael's answer got me on track but I implemented it a little differently. I ended up storing the value as a string in a private property and using it as a "Backing Field". The ExtendedData property then converted JObject to a string on set and vice versa on get:

    public class Campaign
    {
        // https://docs.microsoft.com/en-us/ef/core/modeling/backing-field
        private string _extendedData;
    
        [Key]
        public Guid Id { get; set; }
    
        [Required]
        [MaxLength(50)]
        public string Name { get; set; }
    
        [NotMapped]
        public JObject ExtendedData
        {
            get
            {
                return JsonConvert.DeserializeObject(string.IsNullOrEmpty(_extendedData) ? "{}" : _extendedData);
            }
            set
            {
                _extendedData = value.ToString();
            }
        }
    }
    

    To set _extendedData as a backing field, I added this to my context:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()
            .Property("ExtendedDataStr")
            .HasField("_extendedData");
    }
    

    Update: Darren's answer to use EF Core Value Conversions (new to EF Core 2.1 - which didn't exist at the time of this answer) seems to be the best way to go at this point.

提交回复
热议问题