实体框架:以JSON格式存储实体属性 [英] Entity Framework: Store entity property in json format
问题描述
让说,你已经有类型为的ICollection℃的属性的实体;串>
我要存储为 VARCHAR
在JSON格式的SQL Server。
Let's say you've an entity that has a property typed as ICollection<string>
and I want to store it as varchar
in SQL Server in JSON format.
如何实现这一目标?
感谢您提前。
推荐答案
也许你应该有另一种在你的模型类的字符串属性来保存字符串的集合的JSON represntation。和属性将被映射到你的表。不要将集合属性表的映射。事情是这样的。
Probably You should have another string property in your Model class to hold the JSON represntation of the Collection of string. and that property will be mapped to your Table. Do not map the Collection property to your Table. Something like this
public class Customer
{
public int ID { set;get;}
public string JsonData { set;get;}
[NotMapped]
public ICollection<string> Items { set;get;}
}
和之前的数据saivng你的表,你需要通过阅读项目
PROPERT价值,填补了 JsonData
属性值。
And Before saivng the data to your table, You need to fill the JsonData
property value by reading the Items
Propert value.
JavaScriptSerializer ser= new JavaScriptSerializer();
string JsonData= ser.Serialize(Items);
Bytheway,你确定你想存储的 JSON
表中的代表性?为什么不使用主 - 详细的办法。 JSON数据存储到规范化的表。每当你要建立的JSON回来,你能做到这一点在C#。
Bytheway, Are you sure you want to store the JSON
representation in the table ? Why not use Master - details approach. store the JSON data into normalized tables. Whenever you want to build the JSON back, you can do it in C#.
这篇关于实体框架:以JSON格式存储实体属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!