menu

  public class Menu
    {   /// <summary>
        /// id
        /// </summary>
        [Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), JsonIgnore]
        public int id { set; get; }
        /// <summary>
        /// 名称
        /// </summary>
        [MaxLength(100), Required]
        public string name { set; get; }
   /// <summary>
        /// 属性
        /// </summary>
        public virtual Meta meta{ get; set; }
}
meta

  public class Meta
    { 
        /// <summary>
        /// 名称
        /// </summary>
        [MaxLength(150), Required]
        public string title { set; get; }
        /// <summary>
        /// 图标
        /// </summary>
        [MaxLength(150)]
        public string icon { set; get; }
        /// <summary>
        /// 隐藏
        /// </summary>
        public bool? hidden { set; get; }
}
//EF  [Owned] 已拥有

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Menu>().OwnsOne(p => p.meta);
}

//问题 主键ID不自增
id = table.Column<int>(type: "int", nullable: false)
 //丢失
.Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn),
//采用新的方法 属性 Json转对象
            modelBuilder
                .Entity<Menu>() 
                   .Property(e => e.meta)
                    .HasConversion(
                        v => ObjectToJson(v), // 进入 Json转对象
                        v => JsonToObject<Meta>(v), //返回 Json转对象
                        new ValueComparer<Meta>(
                        (c1, c2) => ObjectToJson(c1) == ObjectToJson(c2),
                        c => c == null ? 0 : ObjectToJson(c).GetHashCode(),
                        c => c)
                        );
  /// <summary>
        /// 对象转json
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        protected string ObjectToJson(object obj)
        {
            string result = null;
            try
            {
                result = JsonSerializer.Serialize(obj);


            }
            catch { }

            return result;

        }


        /// <summary>
        /// 把Json文本转为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        protected T JsonToObject<T>(string input)
        {
            try
            {
                return JsonSerializer.Deserialize<T>(input);
            }
            catch
            {
                return default(T);
            }
        }
       

 

posted on 2022-05-09 19:31  金科许俊  阅读(144)  评论(0编辑  收藏  举报