entity framework:以json格式存储实体属性

假设您的实体具有类型为ICollection的属性,并且我希望以JSON格式将其作为varchar存储在SQL Server中。

怎么做到这一点?

先感谢您。

可能你的Model类中应该有另一个字符串属性来保存字符串Collection的JSON represntation。 并且该属性将映射到您的表。 不要将Collection属性映射到表。 像这样的东西

 public class Customer { public int ID { set;get;} public string JsonData { set;get;} [NotMapped] public ICollection Items { set;get;} } 

在将数据提供给表之前,需要通过读取Items JsonData值来填充JsonData属性值。

 JavaScriptSerializer ser= new JavaScriptSerializer(); string JsonData= ser.Serialize(Items); 

顺便提一下,您确定要将JSON表示存储在表中吗? 为什么不使用Master – details方法。 将JSON数据存储到规范化表中。 无论何时想要构建JSON,都可以在C#中完成。