Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 89 additions & 88 deletions blazor/common/data-binding/bind-entity-framework.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,36 @@ documentation: ug

# Bind Data from SQL Server to Syncfusion® Blazor Components

In this section, you can learn how to retrieve data from SQL database using [Entity Framework](https://learn.microsoft.com/en-us/ef/core/) to bind it to the Grid component and perform CRUD operations.
Entity Framework is an open-source object-relational mapper (O/RM) from Microsoft. Entity Framework works with many databases. But here, we are going to discuss the step-by-step procedure to create an Entity Framework using the [MS SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) database and connect it to the Syncfusion<sup style="font-size:70%">&reg;</sup> component to perform CRUD operations in a Blazor Server Application.
This section explains how to retrieve data from a SQL Server database using Entity Framework and bind it to the Blazor Grid component for performing Create, Read, Update, and Delete (CRUD) operations.

Entity Framework is an open-source object-relational mapper (O/RM) developed by Microsoft. It simplifies database access by allowing developers to work with data as strongly typed objects instead of writing raw SQL queries. Entity Framework supports multiple database providers; however, the focus here is on using [MS SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) database.

The following step-by-step procedure demonstrates how to configure Entity Framework with SQL Server and connect it to the Syncfusion<sup style="font-size:70%">&reg;</sup> Grid component in a Blazor Server application to enable CRUD functionality.
## Prerequisite software

The following software are needed
The following software must be installed before working with the Blazor Grid component and Entity Framework integration:

* [Visual Studio 2026](https://visualstudio.microsoft.com/vs/?utm_source=copilot.com)
Required for building and running Blazor Server applications with full development support.
* [.Net10 or later](https://dotnet.microsoft.com/en-us/download/dotnet/10.0?utm_source=copilot.com)
Provides the runtime and SDK necessary for creating Blazor applications.
* [SQL Server](https://www.microsoft.com/en-us/sql-server/sql-server-downloads?utm_source=copilot.com)
Used as the database engine for storing and retrieving application data.

* Visual Studio 2022
* .NET 6.0 or later.
* SQL Server 2019 or later

## Create the database

The first step is to create a Library database and a table named Book to hold a list of books.
Follow these steps to set up the database and table required for storing book records:
1. **Open SQL Server Management Studio (SSMS).** Launch SQL Server to begin working with databases.

* Open SQL Server.
* Now, create a new database named Library.
* Right-click on the created database and select New Query.
* Use the following SQL query to create a table named Book.
2. **Create a new database named `Library`.**
- In the Object Explorer, right-click on **Databases**.
- Select **New Database**.
- Enter `Library` as the database name and click **OK**.
3. **Open a new query window.**
- Right-click on the newly created `Library` database.
- Select **New Query** to open the SQL editor.
4. **Run the following SQL script to create a table named `Book`:**

```
Create Table Book(
Expand Down Expand Up @@ -59,7 +70,7 @@ In the next window, provide the project name as LibraryManagement and click Next

![Give Project name as LibraryManagement in Blazor](../images/project-name.png)

Now, select Target Framework as (.NET 6.0 or .NET 7.0) in the project template and click Create button to create the Blazor Server application.
Now, select Target Framework as (.NET 9.0 or .NET 10.0) in the project template and click Create button to create the Blazor Server application.

![Create Project in Blazor](../images/create-project.png)

Expand Down Expand Up @@ -553,7 +564,7 @@ If you have set the interactivity location to `Per page/component` in the web ap

## Bind data to Blazor DataGrid component using Entity Framework

To consume data from the database using **Entity Framework**, you need to inject the LibraryService into the razor page and assign it to the DataGrid’s datasource variable. Here, the **DataSource** property of the DataGrid component is used to bind the SQL data using Entity Framework in the Server-side application
To consume data from the database using Entity Framework, the `LibraryService` must be injected into the Razor page and assigned to the DataGrid’s `DataSource` property. The `DataSource` property of the DataGrid component is responsible for binding SQL Server data retrieved through Entity Framework in a Blazor Server application, enabling seamless data display and interaction.

{% tabs %}
{% highlight c# tabtitle="Blazor Web App" %}
Expand Down Expand Up @@ -669,10 +680,13 @@ You can enable editing in the grid component using the **GridEditSettings** comp
[Grid Editing in Blazor](https://blazor.syncfusion.com/documentation/datagrid/editing#editing)

Here, inline edit mode and **Toolbar** property are used to show toolbar items for editing.
While using the DataSource property of Grid, changes will be reflected only in the Grid datasource. To reflect them in the database, handle the CRUD operations externally using the OnActionBegin and OnActionComplete events of Grid.
While using the `DataSource` property of the Grid, changes will be reflected only in the Grid’s local datasource. To ensure that changes are also updated in the database, CRUD operations must be handled externally by using the Grid’s row-level events.

- **RowCreated** – Triggered after a new record has been added. This event can be used to insert the new record into the database.
- **RowEdited** – Triggered after an existing record has been modified. This event can be used to update the corresponding record in the database.
- **RowDeleted** – Triggered after a record has been removed. This event can be used to delete the record from the database.

* **OnActionBegin** – This event will be triggered when the action gets initiated. So, while inserting/updating a record, RequestType Save will be sent in the event arguments to save the changes in the database. Similarly, while deleting a record, RequestType as Delete will be initiated to perform actions externally. Since for both Update and Insert action, RequestType will be Save, you can differentiate them by using the Args.Action property, which will indicate the current action.
* **OnActionComplete** – It will be triggered when certain actions are completed. Here, you can refresh the Grid component with an updated datasource to reflect the changes.
By handling these events, the Grid can remain synchronized with the database. The Grid editing and toolbar features can be combined with these row-level events to provide full CRUD functionality with the existing Grid model.

We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionComplete event code with the previous Grid model.

Expand All @@ -690,9 +704,9 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl

<SfGrid DataSource="@LibraryBooks" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })" TValue="Book">
<GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true" Mode="EditMode.Normal"></GridEditSettings>
<GridEvents OnActionBegin="ActionBeginHandler" OnActionComplete="ActionCompleteHandler" TValue="Book"></GridEvents>
<GridEvents RowCreated="RowCreatedHandler" RowEdited="RowEditedHandler" RowDeleted="RowDeletedHandler" TValue="Book"></GridEvents>
<GridColumns>
<GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" IsIdentity="true" Visible="false" ></GridColumn>
<GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" IsIdentity="true" Visible="false"></GridColumn>
<GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn>
<GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn>
<GridColumn Field="@nameof(Book.Quantity)" Width="90" TextAlign="TextAlign.Right"></GridColumn>
Expand All @@ -704,21 +718,27 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl
@code
{
public List<Book> LibraryBooks { get; set; }
protected override async Task OnInitializedAsync ()
protected override async Task OnInitializedAsync()
{
LibraryBooks = await clientlibrary.GetBooks();
}
public async void ActionBeginHandler ( ActionEventArgs<Book> Args )
public void RowCreatedHandler(RowCreatedEventArgs<Book> args)
{
//Will be triggered when CRUD action is initiated
// Initialize default values or cancel adding using args.Cancel.
await clientlibrary.AddBook(args.Data);
}
public async void ActionCompleteHandler ( ActionEventArgs<Book> Args )

public void RowEditedHandler(RowEditedEventArgs<Book> args)
{
//will be triggered when CRUD action is complete.
if (Args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Save))
{
LibraryBooks = await clientlibrary.GetBooks(); //to fetch the updated data from db to Grid
}
// Configure editors or cancel editing using args as needed.
await clientlibrary.UpdateBook(args.Data);
}


public void RowDeletedHandler(RowDeletedEventArgs<Book> args)
{
// Confirm or cancel deletion based on business rules.
await clientlibrary.DeleteBook(args.Data.Id);
}
}
{% endhighlight %}
Expand All @@ -729,9 +749,9 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl

<SfGrid DataSource="@LibraryBooks" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })" TValue="Book">
<GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true" Mode="EditMode.Normal"></GridEditSettings>
<GridEvents OnActionBegin="ActionBeginHandler" OnActionComplete="ActionCompleteHandler" TValue="Book"></GridEvents>
<GridEvents RowCreated="RowCreatedHandler" RowEdited="RowEditedHandler" RowDeleted="RowDeletedHandler" TValue="Book"></GridEvents>
<GridColumns>
<GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" IsIdentity="true" Visible="false" ></GridColumn>
<GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" IsIdentity="true" Visible="false"></GridColumn>
<GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn>
<GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn>
<GridColumn Field="@nameof(Book.Quantity)" Width="90" TextAlign="TextAlign.Right"></GridColumn>
Expand All @@ -742,22 +762,28 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl

@code
{
public IEnumerable<Book> LibraryBooks { get; set; }
protected override void OnInitialized()
public List<Book> LibraryBooks { get; set; }
protected override async Task OnInitializedAsync()
{
LibraryBooks = LibraryService.GetBooks();
LibraryBooks = await LibraryService.GetBooks();
}
public void ActionBeginHandler(ActionEventArgs<Book> Args)
public void RowCreatedHandler(RowCreatedEventArgs<Book> args)
{
//Will be triggered when CRUD action is initiated
// Initialize default values or cancel adding using args.Cancel.
await LibraryService.AddBook(args.Data);
}
public void ActionCompleteHandler(ActionEventArgs<Book> Args)

public void RowEditedHandler(RowEditedEventArgs<Book> args)
{
//will be triggered when CRUD action is complete.
if (Args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Save))
{
LibraryBooks = LibraryService.GetBooks(); //to fetch the updated data from db to Grid
}
// Configure editors or cancel editing using args as needed.
await LibraryService.UpdateBook(args.Data);
}


public void RowDeletedHandler(RowDeletedEventArgs<Book> args)
{
// Confirm or cancel deletion based on business rules.
await LibraryService.DeleteBook(args.Data.Id);
}
}

Expand All @@ -772,34 +798,25 @@ To insert a new row, click the **Add** toolbar button. The new record edit form

![After Clicking a Add button in Blazor](../images/add-row.png)

Clicking the **Update** toolbar button will initiate the insert action in Grid. Now, the **OnActionBegin** event will be triggered with a **RequestType** as **Save**. You can insert the record into the database (Book table) by calling the **InsertBook()** method of the `ClientServices` in Blazor Web App(BlazorWebApp.Shared project) and `LibraryService` in Blazor Server App.
After clicking the **Add** button in Blazor, use the **Update** toolbar button to confirm the insert action. At this point, the **RowCreated** event will be triggered. This event can be used to insert the new record into the database (`Book` table) by calling the `InsertBook()` method of the `ClientServices` in the Blazor Web App (`BlazorWebApp.Shared` project) and the `LibraryService` in the Blazor Server App.Refer to the following code example.


{% tabs %}
{% highlight c# tabtitle="Blazor Web App" %}

public async void ActionBeginHandler ( ActionEventArgs<Book> Args )
public void RowCreatedHandler(RowCreatedEventArgs<Book> args)
{
//Will be triggered when CRUD action is initiated
if (Args.Action == "Add")
{
// Insert the changes into your database here.
await clientlibrary.InsertBook(Args.Data);
}
// Initialize default values or cancel adding using args.Cancel.
await LibraryService.AddBook(args.Data);
}

{% endhighlight %}
{% highlight c# tabtitle="Blazor Server App" %}

public void ActionBeginHandler(ActionEventArgs<Book> Args)
public void RowCreatedHandler(RowCreatedEventArgs<Book> args)
{
if (Args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Save))
{
if (Args.Action == "Add")
{
// Insert the changes into your database here.
LibraryService.InsertBook(Args.Data);
}
}
// Initialize default values or cancel adding using args.Cancel.
await LibraryService.AddBook(args.Data);
}

{% endhighlight %}
Expand All @@ -813,35 +830,25 @@ To edit a row, select any row and click the **Edit** toolbar button. The edit fo

![After Clicking a update button in Blazor](../images/update.png)

Now, the Price column value is changed to 125 from 250. Clicking the **Update** toolbar button will initiate the update action and trigger the OnActionBegin event with **Save RequestType**. Here, you can update the record in the Book table by calling the **UpdateBook()** method of the `ClientServices` in Blazor Web App(BlazorWebApp.Shared project) and `LibraryService` in Blazor Server App when **Args.Action** is **Edit**. Refer to the following code example.
Now, the Price column value is changed to 125 from 250. After modifying the values, click the **Update** toolbar button to confirm the changes. At this point, the **RowEdited** event will be triggered. This event can be used to update the corresponding record in the database (`Book` table) by calling the `UpdateBook()` method of the `ClientServices` in the Blazor Web App (`BlazorWebApp.Shared` project) and the `LibraryService` in the Blazor Server App.Refer to the following code example.


{% tabs %}
{% highlight c# tabtitle="Blazor Web App" %}

public async void ActionBeginHandler ( ActionEventArgs<Book> Args )
public void RowEditedHandler(RowEditedEventArgs<Book> args)
{

if (Args.Action == "Edit")
{
//Update the changes into your database here.
await clientlibrary.UpdateBook(Args.Data.Id, Args.Data);
}

// Configure editors or cancel editing using args as needed.
await clientlibrary.UpdateBook(args.Data);
}

{% endhighlight %}
{% highlight c# tabtitle="Blazor Server App" %}

public void ActionBeginHandler(ActionEventArgs<Book> Args)
public void RowEditedHandler(RowEditedEventArgs<Book> args)
{
if (Args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Save))
{
if (Args.Action == "Edit")
{
//Update the changes into your database here.
LibraryService.UpdateBook(Args.Data.Id, Args.Data);
}
}
// Configure editors or cancel editing using args as needed.
await clientlibrary.UpdateBook(args.Data);
}

{% endhighlight %}
Expand All @@ -853,30 +860,24 @@ The resultant grid will look like below.

### Delete a row

To delete a row, select any row and click the **Delete** toolbar button. Deleting operation will initiate the OnActionBegin event with RequestType as Delete. Now, you can delete the record from the database by calling **DeleteBook()** method of `ClientServices` in Blazor Web App(BlazorWebApp.Shared project) and `LibraryService` in Blazor Server App with the selected record`s primary key value. Refer to the following code example.
To delete a row, select any row and click the **Delete** toolbar button. After confirming the deletion, the **RowDeleted** event will be triggered. This event can be used to remove the record from the database (`Book` table) by calling the `DeleteBook()` method of the `ClientServices` in the Blazor Web App (`BlazorWebApp.Shared` project) and the `LibraryService` in the Blazor Server App.Refer to the following code example.

{% tabs %}
{% highlight c# tabtitle="Blazor Web App" %}

public void ActionBeginHandler(ActionEventArgs<Book> Args)
public void RowDeletedHandler(RowDeletedEventArgs<Book> args)
{
if (Args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Delete))
{
//Remove the record from your database
LibraryService.DeleteBook(Args.Data.Id);
}
// Confirm or cancel deletion based on business rules.
await LibraryService.DeleteBook(args.Data.Id);
}

{% endhighlight %}
{% highlight c# tabtitle="Blazor Server App" %}

public async void ActionBeginHandler ( ActionEventArgs<Book> Args )
public void RowDeletedHandler(RowDeletedEventArgs<Book> args)
{
if (Args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Delete))
{
//Remove the record from your database
await clientlibrary.RemoveBook(Args.Data.Id);
}
// Confirm or cancel deletion based on business rules.
await LibraryService.DeleteBook(args.Data.Id);
}

{% endhighlight %}
Expand Down
Loading