实体框架:以 json 格式存储实体属性 [英] Entity Framework: Store entity property in json format

查看:38
本文介绍了实体框架:以 json 格式存储实体属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个实体,其属性类型为 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 表示.并且该属性将映射到您的表.不要将 Collection 属性映射到您的表.像这样

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

在将数据保存到表格之前,您需要通过读取 Items 属性值来填充 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);

顺便说一下,您确定要将 JSON 表示存储在表中吗?为什么不使用 Master - details 方法.将 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆