JsonProperty.EFCore: Making it easy to work with JSON fields in Entity Framework Core
Tags: entityframework, efcore, json, dotnet
Published: 2023-08-05 14:23:24

## 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](https://www.nuget.org/packages/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](https://www.nuget.org/packages/JsonProperty.EFCore), 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<T> and JsonDictionary<TKey, TValue>, 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:

```cs
public class Product
{
 public int Id { get; set; }
 public string Name { get; set; }
 public JsonDictionary Parameters { get; set; } = new();
}
```

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:

```cs
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();
```

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

```JSON
{
 "Camera": [13.5, "System.Double"],
 "OS": ["Android", "System.String"],
 "Screen": ["1080x900", "System.String"],
 "Storage": [32, "System.Int32"]
}
```

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

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

After this, the JSON field will look like this:

```JSON
{
 "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"]
}
```

**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:

```cs
public class Note
{
 public int Id { get; set; }
 public string Header { get; set; }
 public JsonList<TodoItem> Todos { get; set; } = new();
}
```

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:

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

Now you can use the polymorphic field:

```cs
MyEntity myEntity = new();
myEntity.Content.Serialize(new DerivedType1());
Base val = myEntity.Content.Deserialize();
Console.WriteLine(val is DerivedType1); //true
```

## 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](https://github.com/maxchistt/JsonProperty.EFCore) to learn more and appreciate the project. Happy development!