Certainly! Below is a comprehensive example of a .NET 8 application using Hot Chocolate 13 and Entity Framework Core 8. This application dynamically generates GraphQL types from a JSON file, stores the data in SQL Server using a JSON column, and provides querying capabilities with sorting, filtering, and pagination.
Project Structure
YourProject
│ Program.cs
│ appsettings.json
│
├───Data
│ data.json
│
├───Models
│ Car.cs
│ CarData.cs
│
├───GraphQL
│ CarTypeModule.cs
│ Query.cs
│
└───Data
ApplicationDbContext.cs
1. data.json
Place this file in the Data folder. It contains the sample data to seed the database.
[
{ "Make": "Toyota", "Model": "Camry", "Color": "Red", "Year": 2020 },
{ "Make": "Honda", "Model": "Accord", "Color": "Blue", "Year": 2019 },
{ "Make": "Ford", "Model": "Mustang", "Color": "Black", "Year": 2021 },
{ "Make": "Tesla", "Model": "Model 3", "Color": "White", "Year": 2022 }
]
2. Models
a. CarData.cs
Defines the structure of the car data.
// Models/CarData.cs
using System.Text.Json.Serialization;
namespace YourProject.Models
{
public class CarData
{
[JsonPropertyName("Make")]
public string Make { get; set; }
[JsonPropertyName("Model")]
public string Model { get; set; }
[JsonPropertyName("Color")]
public string Color { get; set; }
[JsonPropertyName("Year")]
public int Year { get; set; }
}
}
b. Car.cs
Represents the Car entity with an Id and a JSON Data column.
// Models/Car.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace YourProject.Models
{
public class Car
{
[Key]
public int Id { get; set; }
// Stores the CarData as a JSON string in the database
public CarData Data { get; set; }
}
}
3. ApplicationDbContext.cs
Configures Entity Framework Core to use SQL Server and maps the Car entity with a JSON column.
// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Newtonsoft.Json;
using YourProject.Models;
namespace YourProject.Data
{
public class ApplicationDbContext : DbContext
{
public DbSet<Car> Cars { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Define a value converter to serialize/deserialize CarData to JSON
var converter = new ValueConverter<CarData, string>(
v => JsonConvert.SerializeObject(v),
v => JsonConvert.DeserializeObject<CarData>(v));
modelBuilder.Entity<Car>(entity =>
{
entity.ToTable("Cars");
entity.HasKey(e => e.Id);
entity.Property(e => e.Data)
.HasConversion(converter)
.HasColumnType("NVARCHAR(MAX)");
});
}
}
}
4. GraphQL Configuration
a. CarTypeModule.cs
Implements ITypeModule to dynamically generate the Car GraphQL type based on the Car model.
// GraphQL/CarTypeModule.cs
using HotChocolate;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using YourProject.Models;
namespace YourProject.GraphQL
{
public class CarTypeModule : ITypeModule
{
public void RegisterTypes(ITypeDiscoveryContext context)
{
context.Register(
new ObjectType<Car>(d => d
.Name("Car")
.Field(f => f.Id)
.Type<NonNullType<IdType>>()
.Description("Unique identifier of the car.")
.Field("make")
.Resolve(c => c.Data.Make)
.Type<NonNullType<StringType>>()
.Description("Maker of the car.")
.Field("model")
.Resolve(c => c.Data.Model)
.Type<NonNullType<StringType>>()
.Description("Model of the car.")
.Field("color")
.Resolve(c => c.Data.Color)
.Type<NonNullType<StringType>>()
.Description("Color of the car.")
.Field("year")
.Resolve(c => c.Data.Year)
.Type<NonNullType<IntType>>()
.Description("Manufacturing year of the car.")
)
);
}
}
}
b. Query.cs
Defines the Query class with a GetCars method that supports sorting, filtering, and pagination.
// GraphQL/Query.cs
using HotChocolate;
using HotChocolate.Data;
using YourProject.Data;
using YourProject.Models;
namespace YourProject.GraphQL
{
public class Query
{
[UsePaging(IncludeTotalCount = true)]
[UseFiltering]
[UseSorting]
public IQueryable<Car> GetCars([Service] ApplicationDbContext dbContext)
{
return dbContext.Cars;
}
}
}
5. Program.cs
Sets up the application, configures services, applies migrations, and seeds the database with data from the JSON file.
// Program.cs
using Microsoft.EntityFrameworkCore;
using YourProject.Data;
using YourProject.GraphQL;
using YourProject.Models;
using Newtonsoft.Json;
// Build the WebApplication
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure Entity Framework Core with SQL Server
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Configure Hot Chocolate GraphQL server
builder.Services
.AddGraphQLServer()
.AddTypeModule<CarTypeModule>() // Register dynamic type module
.AddQueryType<Query>() // Register Query type
.AddFiltering() // Enable filtering
.AddSorting() // Enable sorting
.AddPaging(); // Enable pagination
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();
if (!dbContext.Cars.Any())
{
// Path to the JSON data file
var jsonFilePath = Path.Combine(app.Environment.ContentRootPath, "Data", "data.json");
var jsonData = await File.ReadAllTextAsync(jsonFilePath);
var carsData = JsonConvert.DeserializeObject<List<CarData>>(jsonData);
if (carsData != null)
{
var cars = carsData.Select(cd => new Car { Data = cd });
dbContext.Cars.AddRange(cars);
dbContext.SaveChanges();
}
}
}
// Configure the HTTP request pipeline.
app.MapGraphQL(); // Maps the GraphQL endpoint to /graphql
// Optionally, enable GraphQL Playground for testing
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
app.Run();
6. appsettings.json
Configure the SQL Server connection string. Replace YOUR_SERVER_NAME with your actual SQL Server instance name.
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER_NAME;Database=CarDb;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
7. Entity Framework Core Migrations
To set up the database schema, follow these steps:
-
Install EF Core Tools (if not already installed):
dotnet tool install --global dotnet-ef
-
Add EF Core Packages:
Ensure you have the necessary packages installed via NuGet:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Newtonsoft.Json
You can install them using the .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Newtonsoft.Json
-
Create Initial Migration:
dotnet ef migrations add InitialCreate
-
Apply Migrations:
dotnet ef database update
This will create the Cars table in your CarDb SQL Server database with an Id and Data column.
8. Testing the GraphQL API
After running the application (dotnet run), navigate to the GraphQL Playground (usually at http://localhost:5000/graphql) to test your queries.
a. Sample Query with Pagination, Filtering, and Sorting
query GetCars($first: Int, $skip: Int, $filter: CarFilter, $orderBy: [CarSortInput!]) {
cars(first: $first, skip: $skip, filter: $filter, order: { year: ASC }) {
nodes {
id
make
model
color
year
}
totalCount
}
}
b. Sample Variables
{
"first": 10,
"skip": 0,
"filter": {
"make": { "eq": "Toyota" }
}
}
This query fetches the first 10 cars where the make is "Toyota", skipping the first 0, and ordering them by year in ascending order.
c. Sample Response
{
"data": {
"cars": {
"nodes": [
{
"id": "1",
"make": "Toyota",
"model": "Camry",
"color": "Red",
"year": 2020
}
],
"totalCount": 1
}
}
}
9. Notes and Considerations
-
Filtering and Sorting: Hot Chocolate automatically generates input types based on your schema for filtering and sorting. Ensure that your GraphQL queries use the correct input types.
-
Performance: Storing data in a JSON column can impact performance, especially for large datasets or complex queries. Consider indexing frequently queried fields or using computed columns if performance becomes an issue.
-
Error Handling: Implement proper error handling and validation as needed, especially when dealing with dynamic data.
-
Security: Ensure that your GraphQL API is secured appropriately, using authentication and authorization as required.
10. Dependencies
Ensure the following NuGet packages are installed:
-
Hot Chocolate GraphQL:
dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data
-
Entity Framework Core:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
-
JSON Serialization:
dotnet add package Newtonsoft.Json
Conclusion
This example demonstrates how to dynamically generate GraphQL types from a JSON file, store data in SQL Server using a JSON column, and provide rich querying capabilities with Hot Chocolate and Entity Framework Core. Adjust and expand upon this foundation to fit the specific needs of your application.