Relational databases are commonly used to store application data in structured tables. However, modern applications often work with information that does not always fit neatly into a fixed set of columns. User preferences, product attributes, configuration settings, contact details, and metadata can contain nested objects and collections that vary between records.
Storing every property in a separate database column can make the database schema unnecessarily complicated. Creating additional tables for every small group of related properties can also increase the number of joins required by an application.
JSON columns provide another option. They allow developers to store structured JSON documents inside relational database columns while continuing to use the database's query and transaction capabilities.
Entity Framework Core supports JSON column mapping, allowing developers to work with familiar C# classes instead of manually converting objects into JSON strings. With this approach, EF Core can serialize and deserialize objects, translate LINQ queries that access JSON properties, and track changes to mapped values.
EF Core 7 introduced JSON column support, initially with SQL Server. EF Core 10 improves the experience by supporting complex types mapped to JSON columns. This makes it easier to model nested objects as values without introducing unnecessary entity identities.
This article explains how to map JSON columns to .NET types using EF Core, configure the database model, insert and retrieve JSON data, query nested properties, update values, and choose the right approach for production applications.
What Are JSON Columns in EF Core?
A JSON column stores a structured JSON document inside a column of a relational database table.
Consider a customer record that contains basic information, along with shipping preferences and notification settings.
A traditional relational design might use separate columns:
CREATE TABLE Customers
(
Id INT PRIMARY KEY,
Name NVARCHAR(150),
ShippingStreet NVARCHAR(200),
ShippingCity NVARCHAR(100),
ShippingPostalCode NVARCHAR(20),
EmailNotifications BIT,
SmsNotifications BIT
);This design works well when the structure is stable and the application frequently queries individual values.
However, a customer may have additional preferences, nested settings, or a collection of contact methods. Adding every new property to the table can make the schema difficult to maintain.
A JSON-based design can store related information in one column:
{
"shippingAddress": {
"street": "Main Road",
"city": "Patna",
"postalCode": "800001"
},
"preferences": {
"emailNotifications": true,
"smsNotifications": false
}
}The database table can contain a JSON column alongside normal relational columns.
EF Core allows developers to map this JSON document to a strongly typed .NET object. Application code can then access properties through normal C# syntax rather than manually parsing JSON.
For example:
customer.Details.Preferences.EmailNotificationsThe important advantage is that JSON storage does not require the application to abandon its relational database model. A table can contain regular columns, relationships, and JSON documents together.
Understanding JSON Mapping Approaches in EF Core
EF Core supports several ways to work with JSON data. The right choice depends on the EF Core version, database provider, and whether the application needs to query properties inside the document.
Mapping JSON as a string
The simplest approach is to store JSON in a string property.
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string DetailsJson { get; set; } = "{}";
}EF Core treats DetailsJson as an ordinary string column. The application is responsible for serialization and deserialization.
using System.Text.Json;
var customer = new Customer
{
Name = "John",
DetailsJson = JsonSerializer.Serialize(
new
{
City = "Patna",
NotificationsEnabled = true
})
};This approach is simple and gives developers full control over the JSON representation. However, EF Core does not understand the internal structure of the JSON string as part of its model.
As a result, developers cannot normally write strongly typed LINQ expressions against individual properties inside that string and expect EF Core to translate them into database JSON queries.
This approach is useful when the application only needs to store and retrieve JSON without querying its internal properties through EF Core.
Mapping JSON with owned entity types
EF Core 7 introduced JSON column mapping through owned entity types using the ToJson() configuration.
For example:
modelBuilder.Entity<Customer>()
.OwnsOne(c => c.Details, details =>
{
details.ToJson();
});This approach allows EF Core to understand the structure of the JSON document and translate queries against its properties.
It was an important improvement over storing JSON as an ordinary string.
However, owned entity types still have entity semantics and identity-related behavior. This can make them less suitable for data that represents a value embedded inside another object.
Mapping JSON with complex types
EF Core 10 provides full support for mapping complex types to JSON columns.
Complex types represent values that belong to another entity rather than independent entities with their own identity.
For example, an address can be part of a customer without needing its own primary key or independent database row.
The following configuration maps a complex property to a JSON column:
modelBuilder.Entity<Customer>()
.ComplexProperty(
c => c.ShippingAddress,
address => address.ToJson());EF Core understands the structure of the complex type and can translate queries against its properties.
For new applications using EF Core 10, complex types are generally the recommended approach for JSON documents that represent structured values.
Create a JSON Mapping Example With EF Core 10
Let's build a practical example using a customer management application.
The application stores customer information in a relational table. Each customer also has an address, notification preferences, and a collection of contact methods.
We will store the additional information in a JSON column.
Create the .NET project
Create a new ASP.NET Core Web API project:
dotnet new webapi -n EfCoreJsonDemo
cd EfCoreJsonDemoInstall the EF Core 10 SQL Server provider:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.0For database migrations, install the EF Core design package:
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.0Make sure the EF Core packages and database provider use compatible major versions. EF Core providers generally do not work across different major EF Core versions.
Create the customer model
Create a Customer.cs file:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public CustomerDetails Details { get; set; } = new();
}The Customer class represents the main relational entity. It contains regular database properties such as Id, Name, and Email.
The Details property represents additional structured information that will be stored in a JSON column.
Now create the complex types:
public class CustomerDetails
{
public Address ShippingAddress { get; set; } = new();
public NotificationPreferences Preferences { get; set; } = new();
public List<ContactMethod> ContactMethods { get; set; } = new();
}
public class Address
{
public string Street { get; set; } = string.Empty;
public string City { get; set; } = string.Empty;
public string PostalCode { get; set; } = string.Empty;
}
public class NotificationPreferences
{
public bool EmailNotifications { get; set; }
public bool SmsNotifications { get; set; }
}
public class ContactMethod
{
public string Type { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
}These classes describe the structure of the JSON document.
The address and notification settings are nested objects. The contact methods property is a collection.
EF Core 10 supports mapping complex types to JSON, including nested structured values and supported complex collections. Collection elements should use reference types such as classes rather than value-type structs.
Configure the DbContext
Create a CustomerDbContext.cs file:
using Microsoft.EntityFrameworkCore;
public class CustomerDbContext : DbContext
{
public CustomerDbContext(
DbContextOptions<CustomerDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers => Set<Customer>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>(customer =>
{
customer.HasKey(c => c.Id);
customer.Property(c => c.Name)
.HasMaxLength(150)
.IsRequired();
customer.Property(c => c.Email)
.HasMaxLength(200)
.IsRequired();
customer.ComplexProperty(
c => c.Details,
details => details.ToJson());
});
}
}The important configuration is:
customer.ComplexProperty(
c => c.Details,
details => details.ToJson());The ComplexProperty method tells EF Core that Details is a complex value. The ToJson() method instructs EF Core to store that value as a JSON document in one database column.
EF Core understands the nested structure, including the address, preferences, and contact methods.
Configure the database connection
Add the SQL Server connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=EfCoreJsonDemo;Trusted_Connection=True;TrustServerCertificate=True"
}
}For production applications, store connection strings in a secure configuration provider rather than committing credentials to source control.
Register the DbContext in Program.cs:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<CustomerDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();This configuration uses the SQL Server EF Core provider. The exact JSON column type generated by EF Core depends on the database engine and compatibility configuration.
Create the Database Migration
Once the model and DbContext are configured, create a migration:
dotnet ef migrations add AddCustomerJsonDetailsApply the migration:
dotnet ef database updateEF Core generates a relational table containing the regular customer columns and one column for the JSON document.
With SQL Server 2025 and the appropriate EF Core 10 compatibility configuration, the JSON column can use SQL Server's native json data type.
For older SQL Server versions, JSON is typically stored in a text column such as nvarchar(max) while SQL Server JSON functions are used to query the document.
The generated migration should always be reviewed before applying it to a production database.
Insert Data Into a JSON Column
After configuring the model, inserting a customer is straightforward.
EF Core handles the JSON serialization when saving the entity.
using Microsoft.EntityFrameworkCore;
public class CustomerService
{
private readonly CustomerDbContext _context;
public CustomerService(CustomerDbContext context)
{
_context = context;
}
public async Task<int> CreateCustomerAsync()
{
var customer = new Customer
{
Name = "John Smith",
Email = "[email protected]",
Details = new CustomerDetails
{
ShippingAddress = new Address
{
Street = "Main Road",
City = "Patna",
PostalCode = "800001"
},
Preferences = new NotificationPreferences
{
EmailNotifications = true,
SmsNotifications = false
},
ContactMethods = new List<ContactMethod>
{
new()
{
Type = "Mobile",
Value = "9876543210"
},
new()
{
Type = "Work",
Value = "[email protected]"
}
}
}
};
_context.Customers.Add(customer);
await _context.SaveChangesAsync();
return customer.Id;
}
}There is no need to call JsonSerializer.Serialize() manually.
EF Core understands the configured complex type and handles the conversion to the database JSON representation.
Join the conversation! Your thoughts help the community grow.