Entity Framework: Serialize/Deserialize JSON column behind the scene
Not directly. You must always have your string property present in your class because EF demands it for persistence. You can also have your non mapped MyClass
property but you must manually handle serialization and deserialization and makes those properties in sync.
Naive solution is to implement INotifyPropertyChanged
in your MyClass and ensure that every change in MyClass
value or in any of its properties will trigger JSON serialization to the string property. This naive solution works for some simple problems but in this case it is really bad idea because it can have big performance impact if you modify a lot of properties on assigned MyClass
property.
Another way is using EF's hooks for materialization and saving changes. You will need to handle ObjectContext.ObjectMaterialized
event (you can get ObjectContext
from DbContext
via IObjectContextAdapter
explicitly implemented by DbContext
). In this event handler you will use string property's value and deserialize its content to MyClass
property. You will also have to override DbContext.SaveChanges
where you will look for all Message
instances which should be inserted or updated and use their MyClass
property to get current value and serialize it to string property.
What you are looking for are some complex mapping scenarios or mapped conversions. EF doesn't support them but you can vote for my suggestion on Data UserVoice.