使用实体框架将集合另存为JSON

时间:2015-02-03 19:42:08

标签: c# sql .net json entity-framework

我试图找到一种方法来获得一个集合的对象但是当它保存到数据库时变成一个JSON字符串。我如何设置实体框架6.1来做到这一点?例如:

 public class Company{

    public Company(){
       this.Times = new HashSet<DateTime>();
    }

    public int Id {get;set;}

    public string Name {get;set;}

    public List<DateTime> Times {get;set;}

 }

公司是一个实体对象。我希望Times能够作为json字符串存储在数据库中。我希望它在从数据库中读取时作为日期时间列表进行序列化。我希望将保存列表转换回json字符串并保存。

2 个答案:

答案 0 :(得分:11)

接受回答的问题是EF对列表内容的任何更改(添加,修改或删除条目)都不会被跟踪

以下是我的解决方案,灵感来自this excellent blog post

此类负责序列化和反序列化,以便集合可以存储在父模型的单个列中:

[ComplexType]
public class DateTimeCollection : Collection<DateTime>
{
    public void AddRange(IEnumerable<DateTime> collection)
    {
        foreach (var item in collection)
        {
            Add(item);
        }
    }

    [Column("Times")]
    public string Serialized
    {
        get { return JsonConvert.SerializeObject(this); }
        private set
        {
            if (string.IsNullOrEmpty(value))
            {
                Clear();
                return;
            }

            var items = JsonConvert.DeserializeObject<DateTime[]>(value);
            Clear();
            AddRange(items);
        }
    }
}

那就是它!您现在可以完全按照您的期望在父类上使用此新集合。将跟踪对集合内容的更改。

public class Company{
    // ...
    public DateTimeCollection Times { get; set; }
}

答案 1 :(得分:5)

以下应该有效(我使用Json.Net,但您可以将其更改为任何其他序列化程序):

public class Company
{

    public int Id {get;set;}

    public string Name {get;set;}

    [NotMapped]
    public List<DateTime> Times {get;set;}

    [Column("Times")]
    public string TimesSerialized
    {
        get
        {
            return JsonConvert.SerializeObject(Times);
        }
        set
        {
            Times = string.IsNullOrEmpty(value)
                    ? new List<DateTime>()
                    : JsonConvert.DeserializeObject<List<DateTime>>(value);
        }
    }
}

如果手动映射,也可以将TimesSerialized设为私有。