DEV Community

Cover image for JsonProperty.EFCore: Making it easy to work with JSON fields in Entity Framework Core
Maxim Chistyakov
Maxim Chistyakov

Posted on

JsonProperty.EFCore: Making it easy to work with JSON fields in Entity Framework Core

Introduction

Sometimes developers face the challenge of using JSON fields in Entity Framework Core. The traditional approach using Fluent API requires writing additional code, which can complicate the project. The JsonProperty.EFCore package solves this problem. This article will discuss the benefits of JsonProperty.EFCore and how it simplifies working with JSON fields, making it a convenient tool for developers.

Problem: Complex Management of JSON Fields

Entity Framework Core works well with relational databases, but managing JSON fields can be a challenging task. Setting up Fluent API to map JSON fields to entity properties requires writing extra code, which can increase the project's complexity. Considering the occasional need to store data in JSON format, developers require an efficient solution to integrate JSON fields into EF Core models.

JsonProperty.EFCore: A Simplified Approach

JsonProperty.EFCore offers a new solution for managing JSON fields. It allows using JSON fields in EF Core without the need for complex Fluent API configurations. With this open-source NuGet package, developers can streamline their workflow and focus on creating application logic, bypassing intricate EF Core settings.

Features and Advantages

  • Simple Integration: JsonProperty.EFCore provides a straightforward integration process. Developers simply add the package, use the appropriate directive, and create entity models as usual - no additional setup required for JSON fields.

  • Support for Generic Types: The package supports generic types like JsonEnumerable and JsonDictionary, enabling developers to work effortlessly with custom element types in JSON collections.

  • Seamless JSON Management: With JsonProperty.EFCore, managing JSON fields becomes much easier. Developers can directly add properties of types JsonEnumerable, JsonList, JsonDictionary, or JsonItem to their entity models and effortlessly manage JSON fields.

  • Strict Type Serialization: The package allows developers to enable strict type serialization. When types are included in JSON, it ensures data integrity and a consistent data conversion process.

  • Polymorphism: Strict typing preserves polymorphic types during serialization and deserialization to JSON.

Usage Examples

Let's explore some examples of using JsonProperty.EFCore to demonstrate its usefulness and convenience:

Storage of Product parameters:

Suppose we have a "Product" entity with various parameters saved in JSON fields. With JsonProperty.EFCore, adding and managing these parameters becomes incredibly simple:

public class Product
{
 public int Id { get; set; }
 public string Name { get; set; }
 public JsonDictionary Parameters { get; set; } = new();
}
Enter fullscreen mode Exit fullscreen mode

The notation JsonDictionary is equivalent to JsonDictionary<string, object>. Polymorphism allows storing values of any type in such a dictionary.

Here's an example of managing a JsonDictionary collection:

Product product = new() {
 Name = "Phone", Price = 500.95m, Amount = 21,
 Parameters = { VirtualDictionary = new Dictionary<string, object>() {
   {"Camera", 13.5 },
   {"OS", "Android" },
   {"Screen", "1080x900"},
   {"Storage", 32}
 }}
};
db.Goods.Add(product);
db.SaveChanges();
Enter fullscreen mode Exit fullscreen mode

This will generate the following JSON data for the field if the JsonSettings.StrictTypeSerialization setting is true (by default):

{
 "Camera": [13.5, "System.Double"],
 "OS": ["Android", "System.String"],
 "Screen": ["1080x900", "System.String"],
 "Storage": [32, "System.Int32"]
}
Enter fullscreen mode Exit fullscreen mode

You can also add and edit elements in the JsonDictionary field:

Product product = db.Goods.FirstOrDefault();
product.Parameters.Add("Battery capacity", 3000);
product.Parameters.Edit(dict => {
 dict["Battery capacity"] = 4000;
 dict["Storage"] = 64;
 dict.Add("RAM", 4);
 return dict;
});
Enter fullscreen mode Exit fullscreen mode

After this, the JSON field will look like this:

{
 "Camera": [13.5, "System.Double"],
 "OS": ["Android", "System.String"],
 "Screen": ["1080x900", "System.String"],
 "Storage": [64, "System.Int32"],
 "Battery capacity": [4000, "System.Int32"],
 "RAM": [4, "System.Int32"]
}
Enter fullscreen mode Exit fullscreen mode

Managing TodoItem list:

Suppose we have a "Note" entity with a collection of "TodoItem" elements saved in JSON. JsonProperty.EFCore simplifies working with JSON collections:

public class Note
{
 public int Id { get; set; }
 public string Header { get; set; }
 public JsonList<TodoItem> Todos { get; set; } = new();
}
Enter fullscreen mode Exit fullscreen mode

In the JsonList<TodoItem> collection, you can also store elements of types derived from TodoItem.

Simple Addition of Polymorphic Field:

Suppose we need to add a field to our entity with an abstract or simply polymorphic type without creating a complex system of entities and tables for derived types. JsonProperty.EFCore with JsonItem is perfect for this:

using JsonProperty.EFCore;
class MyEntity
{
 public int Id { get; set; }
 public int Title { get; set; }
 public JsonItem<Base> Content { get; set; } = new();
}
Enter fullscreen mode Exit fullscreen mode

Now you can use the polymorphic field:

MyEntity myEntity = new();
myEntity.Content.Serialize(new DerivedType1());
Base val = myEntity.Content.Deserialize();
Console.WriteLine(val is DerivedType1); //true
Enter fullscreen mode Exit fullscreen mode

Conclusion

JsonProperty.EFCore is a valuable open-source project that simplifies managing JSON fields in Entity Framework Core. By eliminating the need for Fluent API configurations, it allows developers to work more easily with JSON fields, providing simplicity and efficiency in development. The straightforward integration and support for generic and polymorphic types make JsonProperty.EFCore a useful tool for application developers.

If you want to simplify the management of JSON fields in EF Core, give JsonProperty.EFCore a try. Visit the GitHub repository to learn more and appreciate the project. Happy development!

Top comments (0)