Save Collection as JSON with Entity Framework

I am trying to find a way to have an object that is a collection, but when it is stored in the database, it becomes a JSON string. How can I configure entity 6.1 infrastructure for this? Example:

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

The company is the object of the facility. I would like Times to be stored in the database as a json string once. I would like it to be serialized when reading from the database as a list of dates. I would like the list in save to be converted back to json string and saved.

+5
source share
2 answers

The following should work (I used Json.Net, but you can change it to any other serializer):

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

You can also make TimesSerialized private if you map it manually.

+2
source

The problem with the accepted answer is that any changes to the contents of the list (adding, changing or deleting entries) will not be tracked using EF.

Here is my solution inspired by this great blog post .

This class performs serialization and deserialization, so the collection can be stored in one column of the parent model:

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

What is it! Now you can use this new collection in your parent class exactly as you expected. Changes to the contents of the collection will be tracked.

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

Source: https://habr.com/ru/post/1212562/


All Articles