Skip to content

About

Blazor sample that binds a SQL database to the Syncfusion Blazor Pivot Table using Entity Framework and performs CRUD operations (insert, update, delete) with drill-through editing.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

Repository files navigation

Blazor Pivot Table – SQL Server Database Connection using Entity Framework Core

Project Overview

This repository demonstrates a production-ready pattern for binding a Microsoft SQL Server database to the Syncfusion Blazor Pivot Table using the URL Adaptor. The sample reads and manages order records stored in a SQL Server table through an ASP.NET Core application and Entity Framework Core.

The implementation follows a clean data flow where the Pivot Table interacts with a web API endpoint, and the API uses Entity Framework Core to communicate with SQL Server. This approach keeps the UI focused on analysis while the server handles data access and persistence.

Key Features

  • SQL Server integration with Entity Framework Core
  • Syncfusion Blazor Pivot Table support for aggregation and drill-through
  • URL Adaptor-based remote data binding
  • CRUD operations through the API layer
  • Primary key configuration for drill-through editing
  • Configurable development port through launch settings

Repository

Sample Location / Source Code: https://github.com/SyncfusionExamples/syncfusion-blazor-pivot-table-entity-framework-multi-database-binding-sample

Prerequisites

Component Version Purpose
Visual Studio 2022 / VS Code Latest Development IDE with Blazor workload
.NET SDK net10.0 or compatible Runtime and build tools
Microsoft SQL Server 2019 or later Relational database server
Microsoft.EntityFrameworkCore.SqlServer Latest SQL Server provider for Entity Framework Core
Microsoft.EntityFrameworkCore.Tools Latest EF Core tooling support
Syncfusion.Blazor.PivotTable Latest Pivot Table UI component
Syncfusion.Blazor.Themes Latest Styling for the Pivot Table component
Syncfusion.Blazor.Data Latest Data adaptors including URL Adaptor support
Newtonsoft.Json Latest JSON serialization for CRUD models

Entity Framework Core

Entity Framework Core is the object-relational mapper used in this sample to connect the Blazor application to SQL Server. Instead of writing SQL statements directly for every operation, the controller uses strongly typed entity objects and EF Core manages the data access layer.

The Order entity is mapped to the Orders table through ApplicationDbContext, and EF Core handles database connections, change tracking, and SQL generation for the sample.

DbContext

The ApplicationDbContext class is the central component for EF Core configuration. It exposes a DbSet for the Orders table and connects the application to SQL Server by using the configured connection string.

using Microsoft.EntityFrameworkCore;
using PivotTableMSSQLEFCore.Models;

namespace PivotTableMSSQLEFCore.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(
            DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Order> Orders { get; set; }
    }
}

Entity Model

The Order model represents a single row in the SQL Server Orders table.

using System.ComponentModel.DataAnnotations;

namespace PivotTableMSSQLEFCore.Models
{
    public class Order
    {
        [Key]
        public int? OrderID { get; set; }

        public string? CustomerName { get; set; }

        public int? EmployeeID { get; set; }

        public decimal? Freight { get; set; }

        public string? ShipCity { get; set; }
    }
}

SQL Server Setup

1. Start the SQL Server Service

Ensure the SQL Server service is running on your machine. The sample expects the SQL Server instance to be reachable through the connection string value configured in the application.

Verify the service status with:

Get-Service -Name *SQL*
Start-Service -Name 'MSSQLSERVER'
# or, for a named instance:
# Start-Service -Name 'MSSQL$SQLEXPRESS'

2. Create the Database

Connect to SQL Server and create the database:

CREATE DATABASE OrderDB;
GO

3. Create the Table

Switch to the OrderDB database and create the Orders table used by the sample:

USE OrderDB;
GO

CREATE TABLE Orders
(
    OrderID        INT IDENTITY(1, 1) PRIMARY KEY,
    CustomerName   VARCHAR(100) NULL,
    EmployeeID     INT NULL,
    ShipCity       VARCHAR(100) NULL,
    Freight        DECIMAL(10, 2) NULL
);
GO

4. Insert Sample Data (Optional)

Seed the table with a few rows so the Pivot Table has data to render on first load:

INSERT INTO Orders (CustomerName, EmployeeID, ShipCity, Freight) VALUES
('Toms',   1, 'New York',  35.30),
('Ravi',   2, 'London',    80.20),
('Sven',   1, 'Berlin',    52.10),
('Sara',   3, 'Madrid',    18.40),
('Paul',   2, 'Tokyo',     64.75);
GO

5. Configure the Connection String

The connection string is defined in appsettings.json under the SQLServer key:

{
  "ConnectionStrings": {
    "SQLServer": "Server=<SERVER_NAME>;Database=<DATABASE_NAME>;User Id=<USER_ID>;Password=<PASSWORD>;TrustServerCertificate=True;"
  }
}

Update the values to match your local SQL Server installation:

Property Description
Server SQL Server host or named instance
Database Target database name
User Id SQL Server login with read/write privileges
Password Password for the SQL Server login
TrustServerCertificate Required when encrypting connections without a trusted certificate chain

Project Structure

File/Folder Purpose
/Controllers/OrderController.cs REST API controller exposing read and CRUD endpoints using Entity Framework Core
/Models Contains the Order entity model
/Data Contains ApplicationDbContext for database access
/Components/Pages/Home.razor Pivot Table page with URL Adaptor configuration, editing, and drill-through setup
/Program.cs Service registration for ASP.NET Core, Syncfusion Blazor, and EF Core
/Properties/launchSettings.json Port configuration for the local development server
/PivotTableMSSQLEFCore.csproj Project file with Syncfusion Blazor packages and EF Core NuGet references

Application Flow

The sample follows a straightforward server-driven data flow:

Blazor Pivot Table
        ↓
ASP.NET Core Controller
        ↓
ApplicationDbContext
        ↓
Entity Framework Core
        ↓
      MSSQL
  1. The Pivot Table raises a data request through SfDataManager.
  2. SfDataManager posts the request to the URL Adaptor endpoint.
  3. The OrderController uses ApplicationDbContext to read or modify data through Entity Framework Core.
  4. Entity Framework Core translates the operations into SQL statements and executes them against SQL Server.
  5. The response is returned to the client in the format expected by the Pivot Table.

Configuration Steps

Database Configuration

Create the OrderDB database and the Orders table as described in the SQL Server Setup section, then verify connectivity with sqlcmd:

sqlcmd -S <SERVER_NAME> -U <USER_ID> -P <PASSWORD> -Q "USE OrderDB; SELECT COUNT(*) FROM Orders;"

Connection String Setup

Update the SQLServer entry in appsettings.json to match your SQL Server credentials:

{
  "ConnectionStrings": {
    "SQLServer": "Server=<SERVER_NAME>;Database=OrderDB;User Id=<USER_ID>;Password=<PASSWORD>;TrustServerCertificate=True;"
  }
}

Dependency Injection Registration

Program.cs registers the services required by the sample:

using Microsoft.EntityFrameworkCore;
using PivotTableMSSQLEFCore.Components;
using PivotTableMSSQLEFCore.Data;
using Syncfusion.Blazor;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSyncfusionBlazor();

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddControllers();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("SQLServer")));

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();

app.MapControllers();

app.UseAntiforgery();

app.MapStaticAssets();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

Controller Configuration

The controller routes are defined in Controllers/OrderController.cs. The implementation uses the ApplicationDbContext instance injected by ASP.NET Core and performs CRUD operations through EF Core.

using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
using PivotTableMSSQLEFCore.Data;
using PivotTableMSSQLEFCore.Models;
using Syncfusion.Blazor.Data;
using Syncfusion.Blazor;

namespace PivotTableMSSQLEFCore.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrderController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public OrderController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        public object Post([FromBody] DataManagerRequest request)
        {
            _ = request;

            List<Order> dataSource = GetOrderData();

            return new
            {
                result = dataSource,
                count = dataSource.Count
            };
        }

        private List<Order> GetOrderData()
        {
            return context.Orders
                .OrderBy(o => o.OrderID)
                .ToList();
        }

        [HttpPost("Insert")]
        public IActionResult Insert([FromBody] CRUDModel<Order> value)
        {
            if (value.Value is not Order order
                || string.IsNullOrWhiteSpace(order.CustomerName)
                || !order.EmployeeID.HasValue)
            {
                return BadRequest(
                    "CustomerName and EmployeeID are required.");
            }

            context.Orders.Add(order);
            context.SaveChanges();

            return Ok(order);
        }

        [HttpPost("Update")]
        public IActionResult Update([FromBody] CRUDModel<Order> value)
        {
            if (value.Value is not Order order
                || !order.OrderID.HasValue
                || string.IsNullOrWhiteSpace(order.CustomerName)
                || !order.EmployeeID.HasValue)
            {
                return BadRequest(
                    "OrderID, CustomerName and EmployeeID are required.");
            }

            Order? existingOrder = context.Orders
                .FirstOrDefault(o => o.OrderID == order.OrderID);

            if (existingOrder == null)
            {
                return NotFound();
            }

            existingOrder.CustomerName = order.CustomerName;
            existingOrder.EmployeeID = order.EmployeeID;
            existingOrder.Freight = order.Freight;
            existingOrder.ShipCity = order.ShipCity;

            context.SaveChanges();

            return Ok(existingOrder);
        }

        [HttpPost("Delete")]
        public IActionResult Delete([FromBody] CRUDModel<Order> value)
        {
            if (!int.TryParse(value.Key?.ToString(), out int orderId))
            {
                return BadRequest(
                    "A numeric order key is required.");
            }

            Order? order = context.Orders
                .FirstOrDefault(o => o.OrderID == orderId);

            if (order == null)
            {
                return NotFound();
            }

            context.Orders.Remove(order);
            context.SaveChanges();

            return NoContent();
        }

        public class CRUDModel<T> where T : class
        {
            [JsonPropertyName("action")]
            public string? Action { get; set; }

            [JsonPropertyName("keyColumn")]
            public string? KeyColumn { get; set; }

            [JsonPropertyName("key")]
            public object? Key { get; set; }

            [JsonPropertyName("value")]
            public T? Value { get; set; }

            [JsonPropertyName("added")]
            public List<T>? Added { get; set; }

            [JsonPropertyName("changed")]
            public List<T>? Changed { get; set; }

            [JsonPropertyName("deleted")]
            public List<T>? Deleted { get; set; }

            [JsonPropertyName("params")]
            public IDictionary<string, object>? Params { get; set; }
        }
    }
}

Getting Started / Quick Start

  1. Clone or open the repository in Visual Studio or VS Code.

  2. Restore packages and build.

    dotnet restore
    dotnet build
  3. Start SQL Server and seed the database.

  4. Run the application.

    dotnet run
  5. Open the local URL displayed in the terminal.

CRUD Operations

The sample supports full CRUD operations through the URL Adaptor. Each operation is handled by a dedicated controller endpoint and persisted by Entity Framework Core.

Read

Purpose: Load the orders collection for the Pivot Table.

Flow: The Pivot Table posts a DataManagerRequest to POST /api/Order. The controller retrieves the records through Entity Framework Core.

private List<Order> GetOrderData()
{
    return context.Orders
        .OrderBy(o => o.OrderID)
        .ToList();
}

How EF Core works: The query is translated into a SQL SELECT statement and the results are materialized as Order objects.

Insert

Purpose: Add a new order record.

Flow: The Pivot Table posts a new record to POST /api/Order/Insert. The controller validates the data and adds the entity to the EF Core context.

context.Orders.Add(order);
context.SaveChanges();

How EF Core works: EF Core creates an INSERT statement and persists the new row in SQL Server.

Update

Purpose: Modify an existing order record.

Flow: The Pivot Table posts updated values to POST /api/Order/Update. The controller locates the entity, updates its values, and saves the changes.

existingOrder.CustomerName = order.CustomerName;
existingOrder.EmployeeID = order.EmployeeID;
existingOrder.Freight = order.Freight;
existingOrder.ShipCity = order.ShipCity;

context.SaveChanges();

How EF Core works: EF Core tracks the modified entity and issues an UPDATE statement when SaveChanges is called.

Delete

Purpose: Remove an existing order record.

Flow: The Pivot Table sends a delete request to POST /api/Order/Delete. The controller finds the entity and removes it from the EF Core context.

context.Orders.Remove(order);
context.SaveChanges();

How EF Core works: EF Core issues a DELETE statement for the selected row in SQL Server.

Drill-Through to Source Records

  1. Double-click an aggregated value cell in the pivot view.
  2. A drill-through grid opens showing the underlying SQL Server records.
  3. The BeginDrillThrough event handler marks the OrderID column as IsPrimaryKey = true so CRUD operations target the correct record.
  4. Close the drill-through window to return to the pivot view.

API Endpoints

Endpoint HTTP Method Request Body Description
/api/Order POST DataManagerRequest Returns the Orders collection as { result, count } for Pivot Table binding
/api/Order/Insert POST CRUDModel Inserts a new order record into SQL Server
/api/Order/Update POST CRUDModel Updates an existing order record in SQL Server
/api/Order/Delete POST CRUDModel Deletes an order record from SQL Server using the Key field

Data Model

The Order model represents a single row in the SQL Server Orders table:

public class Order
{
    [Key]
    public int? OrderID { get; set; }
    public string? CustomerName { get; set; }
    public int? EmployeeID { get; set; }
    public decimal? Freight { get; set; }
    public string? ShipCity { get; set; }
}
Field Type Pivot Role Description
OrderID int Primary Key Unique identifier for the order
CustomerName string Row Customer name used as a pivot row field
EmployeeID int Column Employee ID used as a pivot column field
Freight decimal Value Freight amount used as the pivot value
ShipCity string Dimension Ship city used as an additional pivot field

Static Assets

Components/App.razor references the Syncfusion stylesheet and script bundle:

<link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>

If CSS or scripts fail to load, check the browser developer tools for 404 errors on _content/Syncfusion.* paths.

Troubleshooting

Connection Error

  • Verify the Server, Database, User Id, and Password in appsettings.json match your SQL Server installation.
  • Confirm the SQL Server service is running and reachable.
  • Test the connection from sqlcmd using the same credentials.
  • Ensure the database login has read/write privileges on the Orders table.

Application Not Starting

  • Confirm the development port in Properties/launchSettings.json is available.
  • If needed, change the port numbers in launchSettings.json and restart the application.

Full Documentation

For step-by-step guidance on integrating SQL Server with the Syncfusion Blazor Pivot Table, including URL Adaptor configuration, CRUD operations, and database connectivity, see the official Syncfusion Blazor Pivot Table documentation: https://help.syncfusion.com/grid-sdk/blazor/pivot-table/connecting-to-orm/entityframework

Support and Feedback

License

This is a Syncfusion sample project provided to demonstrate product usage. Review the Syncfusion license terms before using Syncfusion components in your own applications.

About

Blazor sample that binds a SQL database to the Syncfusion Blazor Pivot Table using Entity Framework and performs CRUD operations (insert, update, delete) with drill-through editing.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages