-
Notifications
You must be signed in to change notification settings - Fork 73
1005009: Need to create documentation for MySQL server integrate with DataGrid #7442
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
Build Status: INPROGRESS 🔃 |
|
CI Status: FAILURE ❌ |
|
Build Status: INPROGRESS 🔃 |
|
CI Status: FAILURE ❌ |
|
Build Status: INPROGRESS 🔃 |
|
CI Status: FAILURE ❌ |
|
Build Status: INPROGRESS 🔃 |
|
CI Status: FAILURE ❌ |
|
rebuild |
|
Build Status: INPROGRESS 🔃 |
|
CI Status: SUCCESS ✅ |
…ontent/blazor-docs into 1005009-MySqlSample
…ctionsAsync exactly like in sample
…ontent/blazor-docs into 1005009-MySqlSample
Venkat-Ayothi
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changes are fine
Venkat-Ayothi
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changes are fine.
layout: post
title: Blazor Data Grid connected to MySQL via Entity Framework | Syncfusion
description: Bind MySQL data to Blazor Data Grid using Entity Framework Core with complete CRUD, filtering, sorting, paging, and advanced data operations.
platform: Blazor
control: DataGrid
documentation: ug
Connecting MySQL Server to Blazor Data Grid Using Entity Framework
The Syncfusion® Blazor DataGrid supports binding data from a MySQL Server database using Entity Framework Core (EF Core). This modern approach provides a more maintainable and type-safe alternative to raw SQL queries.
What is Entity Framework Core?
Entity Framework Core (EF Core) is a software tool that simplifies database operations in .NET applications. It serves as a bridge between C# code and databases like MySQL.
Key Benefits of Entity Framework Core
What is Pomelo MySQL?
Pomelo MySQL is a software library that helps .NET applications work with a MySQL database using Entity Framework Core. It acts as a bridge between Entity Framework Core and MySQL, allowing applications to read, write, update, and delete data in a MySQL database.
Prerequisites
Ensure the following software and packages are installed before proceeding:
Setting Up the MySQL Environment for Entity Framework Core
Step 1: Create the database and Table in MySQL server
First, the MySQL database structure must be created to store transaction records.
Instructions:
transactiondb.transactionstable with the specified schema.Run the following SQL script:
After executing this script, the transaction records are stored in the
transactionstable within thetransactiondbdatabase. The database is now ready for integration with the Blazor application.Step 2: Install Required NuGet Packages
Before installing the necessary NuGet packages, a new Blazor Web Application must be created using the default template.
This template automatically generates essential starter files—such as Program.cs, appsettings.json, the wwwroot folder, and the Components folder.
For this guide, a Blazor application named Transaction has been created. Once the project is set up, the next step involves installing the required NuGet packages. NuGet packages are software libraries that add functionality to the application. These packages enable Entity Framework Core and MySQL integration.
Method 1: Using Package Manager Console
Method 2: Using NuGet Package Manager UI
All required packages are now installed.
Step 3: Create the Data Model
A data model is a C# class that represents the structure of a database table. This model defines the properties that correspond to the columns in the
transactionstable.Instructions:
Datain the Blazor application project.Datafolder, create a new file named TransactionModel.cs.Explanation:
[Key]attribute marks theIdproperty as the primary key (a unique identifier for each record).?symbol indicates that a property is nullable (can be empty).The data model has been successfully created.
Step 4: Configure the DbContext
A
DbContextis a special class that manages the connection between the application and the MySQL database. It handles all database operations such as saving, updating, deleting, and retrieving data.Instructions:
Datafolder, create a new file named TransactionDbContext.cs.TransactionDbContextclass with the following code:Explanation:
DbContextclass inherits from Entity Framework'sDbContextbase class.Transactionsproperty represents thetransactionstable in the database.OnModelCreatingmethod configures how the database columns should behave (maximum length, required/optional, default values, etc.).The TransactionDbContext class is required because:
Without this class, Entity Framework Core will not know where to save data or how to create the transactions table. The DbContext has been successfully configured.
Step 5: Configure the Connection String
A connection string contains the information needed to connect the application to the MySQL database, including the server address, port, database name, and credentials.
Instructions:
appsettings.jsonfile in the project root.ConnectionStringssection with the MySQL connection details:{ "ConnectionStrings": { "DefaultConnection": "Server=localhost;Port=3306;Database=transactiondb;Uid=root;Pwd=Amrish_arjun11;SslMode=None;ConvertZeroDateTime=false;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }Connection String Components:
localhostfor local development)3306)transactiondb)root)Nonefor local development)The database connection string has been configured successfully.
Step 6: Create the Repository Class
A repository class is an intermediary layer that handles all database operations. This class uses Entity Framework Core to communicate with the database.
Instructions:
Datafolder, create a new file named TransactionRepository.cs.The repository class has been created.
Step 7: Register Services in Program.cs
The
Program.csfile is where application services are registered and configured. This file must be updated to enable Entity Framework Core and the repository pattern.Instructions:
Program.csfile at the project root.var builder = WebApplication.CreateBuilder(args);:The service registration has been completed successfully.
Integrating Syncfusion Blazor DataGrid
Step 1: Install and Configure Blazor DataGrid Components
Syncfusion is a library that provides pre-built UI components like DataGrid, which is used to display data in a table format.
Instructions:
Components/_Imports.razorfile:Components/App.razorfile. Find the<head>section and add:Syncfusion components are now configured and ready to use. For additional guidance, refer to the Grid component’s getting‑started documentation.
Step 2: Update the Blazor DataGrid in the Home Component
The Home component will display the transaction data in a Syncfusion Blazor DataGrid with search, filter, sort, and pagination capabilities.
Instructions:
Home.razorin theComponents/Pagesfolder.Component Explanation:
@rendermode InteractiveServer: Enables interactive server-side rendering for the component.@inject TransactionRepository: Injects the repository to access database methods.<SfGrid>: The DataGrid component that displays data in rows and columns.<GridColumns>: Defines individual columns in the DataGrid.<GridPageSettings>: Configures pagination with 10 records per page.The Home component has been updated successfully with DataGrid.
Step 3: Implement the CustomAdaptor
The Syncfusion® Blazor DataGrid can bind data from a MySQL Server database using DataManager and set the Adaptor property to CustomAdaptor for scenarios that require full control over data operations.
The
CustomAdaptoris a bridge between the DataGrid and the database. It handles all data operations including reading, searching, filtering, sorting, paging, and CRUD operations. Each operation in the CustomAdaptor'sReadAsyncmethod handles specific grid functionality. The Syncfusion® Blazor DataGrid sends operation details to the API through a DataManagerRequest object. These details can be applied to the data source using methods from the DataOperations class.Instructions:
Components/Pages/Home.razorfile.CustomAdaptorclass code inside the@codeblock:The
CustomAdaptorclass has been successfully implemented with all data operations.Common methods in data operations
ReadAsync(DataManagerRequest) - Retrieve and process records (search, filter, sort, page, group)
PerformSearching - Applies search criteria to the collection.
PerformFiltering - Filters data based on conditions.
PerformSorting - Sorts data by one or more fields.
PerformSkip - Skips a defined number of records for paging.
PerformTake - Retrieves a specified number of records for paging.
PerformAggregation – Calculates aggregate values such as Sum, Average, Min, and Max.
Step 4: Add Toolbar with CRUD and search options
The toolbar provides buttons for adding, editing, deleting records, and searching the data.
Instructions:
Components/Pages/Home.razorfile.<SfGrid>component to include the Toolbar property with CRUD and search options:@codeblock:Toolbar Items Explanation:
AddEditDeleteUpdateCancelSearchThe toolbar has been successfully added.
Step 5: Implement Paging Feature
Paging divides large datasets into smaller pages to improve performance and usability.
Instructions:
<SfGrid>component with AllowPaging="true".Update the
ReadAsyncmethod in theCustomAdaptorclass to handle paging:Fetches transaction data by calling the GetTransactionsAsync method, which is implemented in the TransactionRepository.cs file.
How Paging Works:
GridPageSettings).ReadAsyncmethod receives skip and take values.DataOperations.PerformSkip()andDataOperations.PerformTake()methods handle pagination.Paging feature is now active with 10 records per page.
Step 6: Implement Searching feature
Searching allows the user to find records by entering keywords in the search box.
Instructions:
ReadAsyncmethod.Update the
ReadAsyncmethod in theCustomAdaptorclass to handle searching:How Searching Works:
ReadAsyncmethod receives the search criteria indataManagerRequest.Search.DataOperations.PerformSearching()method filters the data based on the search term.Searching feature is now active.
Step 7: Implement Filtering feature
Filtering allows the user to restrict data based on column values using a menu interface.
Instructions:
Components/Pages/Home.razorfile.<SfGrid>component:ReadAsyncmethod in theCustomAdaptorclass to handle filtering:How Filtering Works:
ReadAsyncmethod receives the filter criteria indataManagerRequest.Where.Filtering feature is now active.
Step 8: Implement Sorting feature
Sorting enables the user to arrange records in ascending or descending order based on column values.
Instructions:
Components/Pages/Home.razorfile.<SfGrid>component:ReadAsyncmethod in theCustomAdaptorclass to handle sorting:How Sorting Works:
ReadAsyncmethod receives the sort criteria indataManagerRequest.Sorted.Sorting feature is now active.
Step 9: Implement Grouping feature
Grouping organizes records into hierarchical groups based on column values.
Instructions:
Components/Pages/Home.razorfile.<SfGrid>component:ReadAsyncmethod in theCustomAdaptorclass to handle grouping:How Grouping Works:
ReadAsyncmethod receives the grouping instructions throughdataManagerRequest.Group.Grouping feature is now active.
Step 10: Perform CRUD operations
CustomAdaptor methods enable users to create, read, update, and delete records directly from the DataGrid. Each operation calls corresponding data layer methods in TransactionRepository.cs to execute MySQL commands.
Add the Grid EditSettings and Toolbar configuration to enable create, read, update, and delete (CRUD) operations.
Add the toolbar items list in the
@codeblock:Insert
Record insertion allows new transactions to be added directly through the DataGrid component. The adaptor processes the insertion request, performs any required business‑logic validation, and saves the newly created record to the MySQL Server database.
In Home.razor, implement the
InsertAsyncmethod to handle record deletion within theCustomAdaptorclass:In Data/TransactionRepository.cs, implement the insert method:
What happens behind the scenes:
InsertAsync()method.TransactionRepository.AddTransactionAsync()method is called._context.Transactionscollection.SaveChangesAsync()persists the record to the MySQL database.Now the new transaction is persisted to the database and reflected in the grid.
Update
Record modification allows transaction details to be updated directly within the DataGrid. The adaptor processes the edited row, validates the updated values, and applies the changes to the MySQL Server database while ensuring data integrity is preserved.
In Home.razor, implement the
UpdateAsyncmethod to handle record deletion within theCustomAdaptorclass:In Data/TransactionRepository.cs, implement the update method:
What happens behind the scenes:
UpdateAsync()method is called.TransactionRepository.UpdateTransactionAsync()method is called.SaveChangesAsync()persists the changes to the MySQL database.Now modifications are synchronized to the database and reflected in the grid UI.
Delete
Record deletion allows transactions to be removed directly from the DataGrid. The adaptor captures the delete request, executes the corresponding MySQL DELETE operation, and updates both the database and the grid to reflect the removal.
In Home.razor, implement the
RemoveAsyncmethod to handle record deletion within theCustomAdaptorclass:In Data/TransactionRepository.cs, implement the delete method:
What happens behind the scenes:
RemoveAsync()method is called.TransactionRepository.RemoveTransactionAsync()method is called._context.Transactionscollection.SaveChangesAsync()executes the DELETE statement in MySQL.Now transactions are removed from the database and the grid UI reflects the changes immediately.
Batch update
Batch operations combine multiple insert, update, and delete actions into a single request, minimizing network overhead and ensuring transactional consistency by applying all changes atomically to the MySQL Server database.
In Home.razor, implement the
BatchUpdateAsyncmethod to handle multiple record updates in a single request within theCustomAdaptorclass:What happens behind the scenes:
BatchUpdateAsync()method.TransactionRepository.UpdateTransactionAsync().TransactionRepository.AddTransactionAsync().TransactionRepository.RemoveTransactionAsync().Now the adaptor supports bulk modifications with atomic database synchronization. All CRUD operations are now fully implemented, enabling comprehensive data management capabilities within the Blazor DataGrid.
Reference links
Step 11: Complete code
Here is the complete and final
Home.razorcomponent with all features integrated:Running the Application
Step 1: Build the Application
Step 2: Run the Application
Execute the following command:
Step 3: Access the Application
https://localhost:5001(or the port shown in the terminal).Available Features
Complete Sample Repository
A complete, working sample implementation is available in the GitHub repository.
Summary
This guide demonstrates how to:
The application now provides a complete solution for managing transaction data with a modern, user-friendly interface.