I have a class with a complex object property that has a lot of properties and a lot of nested complex properties in it. Other properties in this class will be stored in SQL the normal way, relational and one column per property. Given the complexity of this particular property, I want to store it as JSON in a column and I need to it to deserialise to a strongly typed object on when I query it. Otherwise I would have to add many tables to store it the relational way.
public class User
{
public Guid Id { get; set; }
public string GivenNames { get; set; }
public string FamilyName { get; set; }
public Transactions Transactions { get; set; }
}
public class Transactions
{
// Lots of properties with complex objects...
}
To achieve the goal above, a custom conversion for this property can be added in the configuration for this entity.
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(e => e.Id);
// Other configurations go here...
builder.Property(e => e.Transactions)
.HasConversion(
v => JsonConvert.SerializeObject(v),
v => v == null
? null
: JsonConvert.DeserializeObject<Transactions>(v));
}
}
That’s it, EF will automatically serialise it to JSON when storing and deserialise to Transactions class when querying it.