Entity Framework: Store entity property in json format

浪尽此生 提交于 2019-12-08 01:46:43

问题


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.

How to achieve this?

Thank you in advance.


回答1:


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;}
}

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, 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#.



来源:https://stackoverflow.com/questions/11759341/entity-framework-store-entity-property-in-json-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!