问题
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