Can I Embed an object in an EF entity (serialize on save, deserialize on access)?

后端 未结 3 1090
广开言路
广开言路 2020-12-08 03:08

I have a class that I want to keep meta data for -- there a several interaction scenarios so meta allows me to keep different meta for different interaction types.



        
3条回答
  •  無奈伤痛
    2020-12-08 03:26

    The feature HasConversion saved my life. Unlock all json formats! Enjoy it!

    public partial class Feed
    {
        public int Id { get; set; }
    
        //this column will be mapped to a "nvarchar(max)" column. perfect!
        public Dictionary Meta { get; set; }
    }
    
    public class FeedsDbContext : DbContext
    {
    
        public FeedsDbContext(DbContextOptions options)
            : base(options)
        {
        }
    
        public virtual DbSet Feed { get; set; }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
    
            builder.Entity(entity =>
            {
                entity.Property(p => p.Meta).HasConversion(
                    x => JsonConvert.SerializeObject(x) //convert TO a json string
                    , x => JsonConvert.DeserializeObject>(x) //convert FROM a json string
                );
            });
        }
    
    }
    

提交回复
热议问题