Skip to content

About

Blazor sample that binds a database to the Syncfusion Blazor Pivot Table using Dapper 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 Dapper

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 application fetches order records stored in a SQL Server table, exposes them through a RESTful ASP.NET Core Web API controller, and binds the result to the Pivot Table on the client through SfDataManager configured with Adaptors.UrlAdaptor.

The implementation shows a clean remote data binding architecture where the Pivot Table never talks to SQL Server directly. Instead, every data operation (read, insert, update, delete) flows through HTTP endpoints handled by the OrderController, which in turn executes queries against SQL Server using Dapper together with the Microsoft.Data.SqlClient provider.

Key Features

  • SQL Server with Dapper Integration: Order records are persisted in a SQL Server table (Orders) and accessed through Dapper for lightweight object mapping.
  • Syncfusion Blazor Pivot Table: Field list, drill-through, and configurable rows, columns, and values for multidimensional analysis.
  • URL Adaptor: Full control over pivot data operations (read and write) through dedicated Url, InsertUrl, UpdateUrl, and RemoveUrl endpoints.
  • Complete CRUD Operations: Add, edit, and delete records directly from the pivot view and the drill-through grid.
  • DataManagerRequest: Structured request object for handling complex pivot data operations, including search, filter, sort, and paging parameters.
  • Primary Key Configuration: The BeginDrillThrough event marks OrderID as the primary key column so that CRUD operations from the drill-through grid target the correct record.
  • Configurable Backend Endpoint: Server port managed via Properties/launchSettings.json.

Repository

Sample Location / Source Code: current project sample implementing SQL Server data access with Dapper.

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 (incl. LocalDB / Express)
Microsoft.Data.SqlClient NuGet package Latest SQL Server ADO.NET data provider
Dapper Latest Lightweight ORM and object mapper for SQL Server
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

Note: Install the latest version of the required Syncfusion Blazor NuGet packages and the latest available versions of Microsoft.Data.SqlClient and Dapper from NuGet. Do not pin to a specific patch version unless required by your project.

SQL Server Setup

1. Start the SQL Server Service

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

Verify the service status with:

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

2. Create the Database

Connect to SQL Server using SQL Server Management Studio, Azure Data Studio, the sqlcmd CLI, or any SQL client 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 configured in appsettings.json under the SQLServer key and read by the controller from configuration:

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

Update the following values to match your local SQL Server installation:

Property Description
Server SQL Server host or named instance (e.g. localhost, localhost\SQLEXPRESS)
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

Windows Authentication alternative: To use Windows Authentication instead of a SQL login, replace the User Id and Password entries with Integrated Security=True;, for example: Server=<SERVER_NAME>;Database=<DATABASE_NAME>;Integrated Security=True;TrustServerCertificate=True;

Project Structure

File/Folder Purpose
/Controllers/OrderController.cs REST API controller exposing read and CRUD endpoints that execute SQL Server queries through Dapper
/Models Contains the Order data model (defined inside OrderController.cs) representing an order record
/Data Data access logic (implemented inline in OrderController.cs via Dapper Query and Execute)
/Repository Repository methods for read/write operations (implemented as controller actions GetOrderData, Insert, Update, Delete)
/Components/Pages/Home.razor Pivot Table page with URL Adaptor configuration, cell editing, and drill-through setup
/Program.cs Service registration for ASP.NET Core, Syncfusion Blazor, and MVC controllers
/Properties/launchSettings.json Port configuration for the local development server
/PivotTableMSSQLDapper.csproj Project file with Syncfusion Blazor packages, Dapper, and Microsoft.Data.SqlClient NuGet references

Application Flow

The sample follows a layered remote data binding architecture:

SQL Server Database  (Orders table)
        ↓
Dapper               (lightweight data access and object mapping)
        ↓
OrderController       (REST API endpoints)
        ↓
UrlAdaptor            (HTTP request/response handling)
        ↓
SfDataManager         (client-side data manager)
        ↓
Blazor Pivot Table    (renders aggregated pivot view)
  1. The Pivot Table raises a data request through SfDataManager.
  2. SfDataManager formats the request as a DataManagerRequest and POSTs it to the Url Adaptor endpoint.
  3. The OrderController receives the request, opens a SqlConnection, and executes the appropriate SQL query against the SQL Server Orders table using Dapper.
  4. The result is serialized into the { result, count } format expected by the Url Adaptor and returned to the client.
  5. The Pivot Table renders the aggregated pivot view from the returned data.

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:

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

app.MapControllers() is called in the middleware pipeline so that OrderController endpoints are reachable from the Pivot Table.

Controller Configuration

The controller routes are defined in /Controllers/OrderController.cs:

Endpoint HTTP Method Purpose
POST /api/Order POST Read endpoint that returns the Orders collection as { result, count }
POST /api/Order/Insert POST Inserts a new order record
POST /api/Order/Update POST Updates an existing order record
POST /api/Order/Delete POST Deletes an order record by OrderID

UrlAdaptor Configuration

The SfDataManager configuration in Components/Pages/Home.razor binds the Pivot Table to the REST backend:

<SfDataManager
    Url="http://localhost:5145/api/Order"
    InsertUrl="http://localhost:5145/api/Order/Insert"
    UpdateUrl="http://localhost:5145/api/Order/Update"
    RemoveUrl="http://localhost:5145/api/Order/Delete"
    Adaptor="Adaptors.UrlAdaptor">
</SfDataManager>
Property Description
Url REST endpoint for reading order records with data operation support (search, filter, sort, paging)
InsertUrl Endpoint for creating new records
UpdateUrl Endpoint for updating existing records
RemoveUrl Endpoint for deleting records
Adaptor Set to Adaptors.UrlAdaptor to enable URL-based data binding

Important: The port in the URLs above (5145) must match the applicationUrl defined in Properties/launchSettings.json. If you change the port, update all four URLs in Home.razor accordingly.

Getting Started / Quick Start

  1. Open the repository in Visual Studio or VS Code.

  2. Restore packages and build

    From the project folder, restore the dependencies:

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

    Ensure SQL Server is running and that the OrderDB database and Orders table exist (see SQL Server Setup).

  4. Run the application

    From the PivotTableMSSQLDapper project folder, start the application with dotnet run:

    dotnet run
  5. Open the application

    Navigate to the local URL displayed in the terminal (typically https://localhost:7169 or http://localhost:5145).

CRUD Operations

The sample supports full CRUD operations through the Url Adaptor. Each operation is routed to a dedicated controller endpoint that executes the corresponding SQL statement against SQL Server using Dapper.

Read

  • The Pivot Table POSTs a DataManagerRequest to POST /api/Order.
  • OrderController.Post calls GetOrderData(), which runs SELECT ... FROM Orders ORDER BY OrderID and returns the mapped list of Order objects.
  • Dapper maps rows from SQL Server into Order instances via connection.Query<Order>(query).
  • The result is returned as { result = orders, count = orders.Count }, which is the format expected by the Url Adaptor.

Insert

  1. Double-click an empty cell in the pivot view value area to open the editor.
  2. Enter a value for the new measure and click Update.
  3. The Pivot Table POSTs the new record to POST /api/Order/Insert.
  4. The controller executes an INSERT INTO Orders (...) statement through Dapper with connection.Execute(query, order).

Update

  1. Double-click any value cell in the pivot view.
  2. Modify the value in the editor dialog and click Update.
  3. The Pivot Table POSTs the updated record to POST /api/Order/Update.
  4. The controller executes an UPDATE Orders SET ... WHERE OrderID = @OrderID statement through Dapper with connection.Execute(query, order).

Delete

  1. Right-click the row or cell to be removed and select the delete option.
  2. Confirm the deletion in the dialog.
  3. The Pivot Table POSTs the record key to POST /api/Order/Delete.
  4. The controller executes a DELETE FROM Orders WHERE OrderID = @OrderID statement through Dapper with connection.Execute(query, new { OrderID = orderId }).

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 that CRUD operations from the drill-through grid uniquely identify 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 full Orders collection as { result, count } for Pivot Table binding
/api/Order/Insert POST CRUDModel<Order> Inserts a new order record into SQL Server
/api/Order/Update POST CRUDModel<Order> Updates an existing order record in SQL Server
/api/Order/Delete POST CRUDModel<Order> 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 (SQL Server IDENTITY)
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 (aggregated measure)
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 (F12) for 404 errors on _content/Syncfusion.* paths.

Troubleshooting

Connection Error

  • Verify Server, Database, User Id, and Password in appsettings.json (the SQLServer connection string) match your SQL Server installation.
  • Confirm the SQL Server service is running and reachable:
    • Windows: Get-Service -Name *SQL* and Start-Service -Name 'MSSQLSERVER' (or 'MSSQL$SQLEXPRESS' for a named instance)
  • Test the connection from the sqlcmd CLI using the same credentials:
    sqlcmd -S <SERVER_NAME> -U <USER_ID> -P <PASSWORD>
  • Ensure the database login has read/write privileges on the Orders table.
  • Include TrustServerCertificate=True in the connection string to avoid certificate errors on local dev instances.

Missing Controllers / Endpoint Not Found

  • Confirm app.MapControllers() is present in Program.cs.
  • Verify all routes (api/Order, api/Order/Insert, api/Order/Update, api/Order/Delete) are defined in OrderController.cs.
  • Check that the URL port in Home.razor matches the running port from launchSettings.json.

Port Already in Use

  • Change the port numbers in Properties/launchSettings.json to available ports.
  • Update the Url, InsertUrl, UpdateUrl, and RemoveUrl properties in Home.razor to match the new port.

Full Documentation

For detailed, step-by-step instructions including complete code examples, controller implementations, connection string configuration, CRUD operations, and advanced SQL Server integration scenarios, refer to the Syncfusion Blazor Pivot Table documentation: https://help.syncfusion.com/grid-sdk/blazor/pivot-table/connecting-to-orm/dapper

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 database to the Syncfusion Blazor Pivot Table using Dapper 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