Certainly! Below is a comprehensive example demonstrating how to create a .NET 8 application using Entity Framework Core 8, Hot Chocolate GraphQL 13, and SQL Server. This application will:
- Define an
Item entity with Id and Data (storing JSON).
- Configure the
DbContext to interact with SQL Server.
- Seed the database with sample JSON data.
- Set up Hot Chocolate GraphQL to enable querying with sorting, filtering, and pagination based on dynamic JSON fields.
Given that the JSON structure in the Data column is dynamic and unknown at compile time, we'll implement dynamic filtering and sorting by allowing clients to specify the JSON path and value for filtering and the JSON path for sorting.
Prerequisites
- .NET 8 SDK installed.
- SQL Server instance running.
- Visual Studio 2022 or any preferred IDE.
Step 1: Create a New ASP.NET Core Web API Project
Open your terminal or command prompt and run:
dotnet new webapi -n DynamicJsonGraphQL
cd DynamicJsonGraphQL
Step 2: Add Necessary NuGet Packages
Run the following commands to add the required packages:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data
dotnet add package Newtonsoft.Json
Step 3: Define the Item Entity
Create a new folder named Models and add Item.cs:
// Models/Item.cs
using System.ComponentModel.DataAnnotations;
namespace DynamicJsonGraphQL.Models
{
public class Item
{
[Key]
public int Id { get; set; }
// Storing JSON data as string
public string Data { get; set; }
}
}
Step 4: Configure the ApplicationDbContext
Create a new folder named Data and add ApplicationDbContext.cs:
// Data/ApplicationDbContext.cs
using DynamicJsonGraphQL.Models;
using Microsoft.EntityFrameworkCore;
namespace DynamicJsonGraphQL.Data
{
public class ApplicationDbContext : DbContext
{
public DbSet<Item> Items => Set<Item>();
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
// Configure the Items table
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Item>(entity =>
{
entity.ToTable("Items");
entity.Property(e => e.Data)
.IsRequired()
.HasColumnType("varchar(max)");
});
base.OnModelCreating(modelBuilder);
}
}
}
Step 5: Define GraphQL Types and Queries
We'll implement a Query type that allows filtering, sorting, and pagination based on dynamic JSON fields.
Create a new folder named GraphQL and add the following files.
5.1. Define Input Types for Filtering and Sorting
// GraphQL/Inputs/ItemFilterInput.cs
using HotChocolate;
namespace DynamicJsonGraphQL.GraphQL.Inputs
{
public class ItemFilterInput
{
// JSON path for filtering, e.g., "$.name"
public string Field { get; set; }
// Value to filter by
public string Value { get; set; }
}
}
// GraphQL/Inputs/ItemSortInput.cs
namespace DynamicJsonGraphQL.GraphQL.Inputs
{
public class ItemSortInput
{
// JSON path for sorting, e.g., "$.age"
public string Field { get; set; }
// Sort direction: "asc" or "desc"
public string Direction { get; set; }
}
}
5.2. Define the Query Type
// GraphQL/Queries/ItemQuery.cs
using DynamicJsonGraphQL.Data;
using DynamicJsonGraphQL.GraphQL.Inputs;
using DynamicJsonGraphQL.Models;
using HotChocolate;
using HotChocolate.Data;
using Microsoft.EntityFrameworkCore;
namespace DynamicJsonGraphQL.GraphQL.Queries
{
public class ItemQuery
{
private readonly ApplicationDbContext _dbContext;
public ItemQuery(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
// Define the GraphQL query for Items with filtering, sorting, and pagination
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<Item> GetItems(
IEnumerable<ItemFilterInput>? filters,
IEnumerable<ItemSortInput>? sorts)
{
IQueryable<Item> query = _dbContext.Items.AsQueryable();
// Apply filters
if (filters != null)
{
foreach (var filter in filters)
{
// Using SQL Server JSON_VALUE to filter
query = query.Where(item =>
EF.Functions.JsonValue(item.Data, filter.Field) == filter.Value);
}
}
// Apply sorts
if (sorts != null)
{
bool firstSort = true;
foreach (var sort in sorts)
{
// Determine if sorting ascending or descending
bool ascending = sort.Direction.ToLower() == "asc";
// Apply sorting using JSON_VALUE
if (firstSort)
{
query = ascending
? query.OrderBy(item => EF.Functions.JsonValue(item.Data, sort.Field))
: query.OrderByDescending(item => EF.Functions.JsonValue(item.Data, sort.Field));
firstSort = false;
}
else
{
query = ascending
? ((IOrderedQueryable<Item>)query).ThenBy(item => EF.Functions.JsonValue(item.Data, sort.Field))
: ((IOrderedQueryable<Item>)query).ThenByDescending(item => EF.Functions.JsonValue(item.Data, sort.Field));
}
}
}
return query;
}
}
}
Explanation:
-
Filtering: For each filter input, we use EF.Functions.JsonValue to extract the value from the JSON Data field using the specified JSON path (filter.Field) and compare it to the provided filter.Value.
-
Sorting: Similarly, for sorting, we extract the value from the JSON Data field and apply ascending or descending order based on the sort.Direction.
-
Pagination: Handled by the [UsePaging] attribute, which provides first, last, before, and after arguments automatically.
Step 6: Set Up Program.cs
Replace the contents of Program.cs with the following code:
// Program.cs
using DynamicJsonGraphQL.Data;
using DynamicJsonGraphQL.GraphQL.Inputs;
using DynamicJsonGraphQL.GraphQL.Queries;
using Microsoft.EntityFrameworkCore;
using HotChocolate;
using HotChocolate.AspNetCore;
using HotChocolate.AspNetCore.Playground;
var builder = WebApplication.CreateBuilder(args);
// Configure SQL Server connection
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Register GraphQL services
builder.Services
.AddGraphQLServer()
.AddQueryType<ItemQuery>()
.AddFiltering()
.AddSorting()
.AddProjections();
// Allow CORS for development purposes
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
// Apply migrations and seed the database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.Migrate();
// Check if database is seeded
if (!dbContext.Items.Any())
{
// Seed with sample data
var sampleItems = new List<DynamicJsonGraphQL.Models.Item>
{
new DynamicJsonGraphQL.Models.Item
{
Data = @"{
""name"": ""Item1"",
""age"": 30,
""attributes"": { ""color"": ""red"", ""size"": ""M"" }
}"
},
new DynamicJsonGraphQL.Models.Item
{
Data = @"{
""name"": ""Item2"",
""age"": 25,
""attributes"": { ""color"": ""blue"", ""size"": ""L"" }
}"
},
new DynamicJsonGraphQL.Models.Item
{
Data = @"{
""name"": ""Item3"",
""age"": 35,
""attributes"": { ""color"": ""green"", ""size"": ""S"" }
}"
},
// Add more items as needed
};
dbContext.Items.AddRange(sampleItems);
dbContext.SaveChanges();
}
}
app.UseCors("AllowAll");
app.MapGraphQL();
// Enable GraphQL Playground at /playground
app.UsePlayground(new PlaygroundOptions
{
Path = "/playground"
});
app.Run();
Explanation:
-
Database Connection: The connection string is set in appsettings.json (to be defined next).
-
GraphQL Server: Configures the GraphQL server with the ItemQuery type and enables filtering, sorting, and projections.
-
CORS: Allows all origins for development. Adjust as needed for production.
-
Database Migration and Seeding: Applies any pending migrations and seeds the database with sample JSON data if it's empty.
-
GraphQL Endpoint: Exposes the GraphQL endpoint and the GraphQL Playground at /playground for testing.
Step 7: Configure the Database Connection
Open appsettings.json and define the connection string to your SQL Server instance:
// appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SQL_SERVER;Database=DynamicJsonGraphQLDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Replace YOUR_SQL_SERVER with your SQL Server name or instance. For example, for a local default instance:
"DefaultConnection": "Server=localhost;Database=DynamicJsonGraphQLDb;Trusted_Connection=True;MultipleActiveResultSets=true"
Step 8: Create and Apply Migrations
Run the following commands to create and apply the initial migration:
dotnet ef migrations add InitialCreate
dotnet ef database update
Make sure you have the EF Core Tools installed. If not, install them using:
dotnet tool install --global dotnet-ef
Step 9: Run the Application
Start the application using:
dotnet run
Navigate to http://localhost:5000/playground (port might differ) to access the GraphQL Playground interface.
Step 10: Sample GraphQL Queries
Here are some sample GraphQL queries demonstrating filtering, sorting, and pagination.
10.1. Fetch All Items with Pagination
query {
getItems(first: 2) {
edges {
node {
id
data
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}
10.2. Filter Items Where attributes.color is red
query {
getItems(filters: [{ field: "$.attributes.color", value: "red" }]) {
edges {
node {
id
data
}
}
}
}
10.3. Sort Items by age Descending
query {
getItems(sorts: [{ field: "$.age", direction: "desc" }]) {
edges {
node {
id
data
}
}
}
}
10.4. Combine Filtering and Sorting with Pagination
query {
getItems(
filters: [{ field: "$.attributes.size", value: "L" }],
sorts: [{ field: "$.name", direction: "asc" }],
first: 10
) {
edges {
node {
id
data
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}
Explanation of JSON Paths:
$.name: Accesses the name field at the root of the JSON.
$.age: Accesses the age field at the root.
$.attributes.color: Accesses the color field inside the attributes object.
Note: The JSON paths used here follow the SQL Server JSON path syntax. Ensure that the paths correctly point to the desired fields in your JSON data.
Step 11: Testing the Application
Use the GraphQL Playground to execute the sample queries above. You should receive responses based on the seeded data.
Example Response for Filtering by attributes.color = red:
{
"data": {
"getItems": {
"edges": [
{
"node": {
"id": 1,
"data": "{ \"name\": \"Item1\", \"age\": 30, \"attributes\": { \"color\": \"red\", \"size\": \"M\" } }"
}
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "YXJyYXljb25uZWN0aW9uOjE="
},
"totalCount": 1
}
}
}
Additional Considerations
-
Performance: Filtering and sorting using JSON functions in SQL Server can be less performant compared to normalized columns. For large datasets or performance-critical applications, consider storing frequently queried fields as separate columns.
-
Security: Allowing clients to specify JSON paths could expose sensitive data or lead to complex queries. Implement necessary validations and restrictions as needed.
-
Error Handling: Enhance the resolvers to handle invalid JSON paths or data types gracefully.
-
Caching: Implement caching strategies if the data does not change frequently to improve performance.
Complete Code Listing
For completeness, here is the entire code structure.
Project Structure
DynamicJsonGraphQL/
├── Data/
│ └── ApplicationDbContext.cs
├── GraphQL/
│ ├── Inputs/
│ │ ├── ItemFilterInput.cs
│ │ └── ItemSortInput.cs
│ └── Queries/
│ └── ItemQuery.cs
├── Models/
│ └── Item.cs
├── Migrations/
│ └── [EF Core migration files]
├── appsettings.json
├── Program.cs
├── DynamicJsonGraphQL.csproj
Models/Item.cs
using System.ComponentModel.DataAnnotations;
namespace DynamicJsonGraphQL.Models
{
public class Item
{
[Key]
public int Id { get; set; }
// Storing JSON data as string
public string Data { get; set; }
}
}
Data/ApplicationDbContext.cs
using DynamicJsonGraphQL.Models;
using Microsoft.EntityFrameworkCore;
namespace DynamicJsonGraphQL.Data
{
public class ApplicationDbContext : DbContext
{
public DbSet<Item> Items => Set<Item>();
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
// Configure the Items table
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Item>(entity =>
{
entity.ToTable("Items");
entity.Property(e => e.Data)
.IsRequired()
.HasColumnType("varchar(max)");
});
base.OnModelCreating(modelBuilder);
}
}
}
GraphQL/Inputs/ItemFilterInput.cs
using HotChocolate;
namespace DynamicJsonGraphQL.GraphQL.Inputs
{
public class ItemFilterInput
{
// JSON path for filtering, e.g., "$.name"
public string Field { get; set; }
// Value to filter by
public string Value { get; set; }
}
}
GraphQL/Inputs/ItemSortInput.cs
namespace DynamicJsonGraphQL.GraphQL.Inputs
{
public class ItemSortInput
{
// JSON path for sorting, e.g., "$.age"
public string Field { get; set; }
// Sort direction: "asc" or "desc"
public string Direction { get; set; }
}
}
GraphQL/Queries/ItemQuery.cs
using DynamicJsonGraphQL.Data;
using DynamicJsonGraphQL.GraphQL.Inputs;
using DynamicJsonGraphQL.Models;
using HotChocolate;
using HotChocolate.Data;
using Microsoft.EntityFrameworkCore;
namespace DynamicJsonGraphQL.GraphQL.Queries
{
public class ItemQuery
{
private readonly ApplicationDbContext _dbContext;
public ItemQuery(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
// Define the GraphQL query for Items with filtering, sorting, and pagination
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<Item> GetItems(
IEnumerable<ItemFilterInput>? filters,
IEnumerable<ItemSortInput>? sorts)
{
IQueryable<Item> query = _dbContext.Items.AsQueryable();
// Apply filters
if (filters != null)
{
foreach (var filter in filters)
{
// Using SQL Server JSON_VALUE to filter
query = query.Where(item =>
EF.Functions.JsonValue(item.Data, filter.Field) == filter.Value);
}
}
// Apply sorts
if (sorts != null)
{
bool firstSort = true;
foreach (var sort in sorts)
{
// Determine if sorting ascending or descending
bool ascending = sort.Direction.ToLower() == "asc";
// Apply sorting using JSON_VALUE
if (firstSort)
{
query = ascending
? query.OrderBy(item => EF.Functions.JsonValue(item.Data, sort.Field))
: query.OrderByDescending(item => EF.Functions.JsonValue(item.Data, sort.Field));
firstSort = false;
}
else
{
query = ascending
? ((IOrderedQueryable<Item>)query).ThenBy(item => EF.Functions.JsonValue(item.Data, sort.Field))
: ((IOrderedQueryable<Item>)query).ThenByDescending(item => EF.Functions.JsonValue(item.Data, sort.Field));
}
}
}
return query;
}
}
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=DynamicJsonGraphQLDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Ensure you replace the DefaultConnection with your actual SQL Server details.
Program.cs
using DynamicJsonGraphQL.Data;
using DynamicJsonGraphQL.GraphQL.Inputs;
using DynamicJsonGraphQL.GraphQL.Queries;
using Microsoft.EntityFrameworkCore;
using HotChocolate;
using HotChocolate.AspNetCore;
using HotChocolate.AspNetCore.Playground;
var builder = WebApplication.CreateBuilder(args);
// Configure SQL Server connection
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Register GraphQL services
builder.Services
.AddGraphQLServer()
.AddQueryType<ItemQuery>()
.AddFiltering()
.AddSorting()
.AddProjections();
// Allow CORS for development purposes
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
// Apply migrations and seed the database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.Migrate();
// Check if database is seeded
if (!dbContext.Items.Any())
{
// Seed with sample data
var sampleItems = new List<DynamicJsonGraphQL.Models.Item>
{
new DynamicJsonGraphQL.Models.Item
{
Data = @"{
""name"": ""Item1"",
""age"": 30,
""attributes"": { ""color"": ""red"", ""size"": ""M"" }
}"
},
new DynamicJsonGraphQL.Models.Item
{
Data = @"{
""name"": ""Item2"",
""age"": 25,
""attributes"": { ""color"": ""blue"", ""size"": ""L"" }
}"
},
new DynamicJsonGraphQL.Models.Item
{
Data = @"{
""name"": ""Item3"",
""age"": 35,
""attributes"": { ""color"": ""green"", ""size"": ""S"" }
}"
},
// Add more items as needed
};
dbContext.Items.AddRange(sampleItems);
dbContext.SaveChanges();
}
}
app.UseCors("AllowAll");
app.MapGraphQL();
// Enable GraphQL Playground at /playground
app.UsePlayground(new PlaygroundOptions
{
Path = "/playground"
});
app.Run();
Conclusion
This example demonstrates how to effectively store dynamic JSON data within a SQL Server database using Entity Framework Core and expose it via a GraphQL API using Hot Chocolate. It allows clients to perform filtering, sorting, and pagination based on dynamic JSON fields without knowing the structure at compile time. Adjust and extend the example as needed to fit your specific requirements.