diff --git a/blazor/common/data-binding/bind-entity-framework.md b/blazor/common/data-binding/bind-entity-framework.md index a1e36fb906..1db33439a4 100644 --- a/blazor/common/data-binding/bind-entity-framework.md +++ b/blazor/common/data-binding/bind-entity-framework.md @@ -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® 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® 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( @@ -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) @@ -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" %} @@ -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. @@ -690,9 +704,9 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl - + - + @@ -704,21 +718,27 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl @code { public List LibraryBooks { get; set; } - protected override async Task OnInitializedAsync () + protected override async Task OnInitializedAsync() { LibraryBooks = await clientlibrary.GetBooks(); } - public async void ActionBeginHandler ( ActionEventArgs Args ) + public void RowCreatedHandler(RowCreatedEventArgs 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 Args ) + + public void RowEditedHandler(RowEditedEventArgs 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 args) + { + // Confirm or cancel deletion based on business rules. + await clientlibrary.DeleteBook(args.Data.Id); } } {% endhighlight %} @@ -729,9 +749,9 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl - + - + @@ -742,22 +762,28 @@ We have added the DataGrid editing, toolbar, and OnActionBegin and OnActionCompl @code { - public IEnumerable LibraryBooks { get; set; } - protected override void OnInitialized() + public List LibraryBooks { get; set; } + protected override async Task OnInitializedAsync() { - LibraryBooks = LibraryService.GetBooks(); + LibraryBooks = await LibraryService.GetBooks(); } - public void ActionBeginHandler(ActionEventArgs Args) + public void RowCreatedHandler(RowCreatedEventArgs 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 Args) + + public void RowEditedHandler(RowEditedEventArgs 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 args) + { + // Confirm or cancel deletion based on business rules. + await LibraryService.DeleteBook(args.Data.Id); } } @@ -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 Args ) +public void RowCreatedHandler(RowCreatedEventArgs 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 Args) +public void RowCreatedHandler(RowCreatedEventArgs 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 %} @@ -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 Args ) +public void RowEditedHandler(RowEditedEventArgs 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 Args) +public void RowEditedHandler(RowEditedEventArgs 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 %} @@ -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 Args) +public void RowDeletedHandler(RowDeletedEventArgs 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 Args ) +public void RowDeletedHandler(RowDeletedEventArgs 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 %} diff --git a/blazor/datagrid/filter-menu.md b/blazor/datagrid/filter-menu.md index c40418e891..f33f00929d 100644 --- a/blazor/datagrid/filter-menu.md +++ b/blazor/datagrid/filter-menu.md @@ -1299,64 +1299,77 @@ In this configuration, the `SfDateRangePicker` is rendered in the filter templat {% tabs %} {% highlight razor tabtitle="Index.razor" %} +@page "/" + @using Syncfusion.Blazor.Calendars @using Syncfusion.Blazor.Data @using Syncfusion.Blazor.Grids - + + TextAlign="Syncfusion.Blazor.Grids.TextAlign.Right" Width="120"> - + @{ - - + + } + TextAlign="Syncfusion.Blazor.Grids.TextAlign.Right" Width="120"> +@if (IsOrderDateCssEnabled) +{ + +} + @code { - - public DateTime StartDate { get; set; } - public DateTime EndDate { get; set; } + + public bool IsOrderDateCssEnabled { get; set; } = false; + + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } public List GridData { get; set; } SfGrid? Grid { get; set; } + SfDateRangePicker DateRangePicker; protected override void OnInitialized() { GridData = OrderData.GetAllRecords(); } - public async Task FilteringHandler(FilteringEventArgs args) - + public async Task FilteringHandler(Syncfusion.Blazor.Grids.FilteringEventArgs args) { if (args.ColumnName == "OrderDate" && args.FilterPredicates != null) { - args.Cancel = true; //cancel default filter action. + + args.Cancel = true; + if (Grid.FilterSettings.Columns == null) { Grid.FilterSettings.Columns = new List(); } - if (Grid.FilterSettings.Columns.Count > 0) - { - Grid.FilterSettings.Columns.RemoveAll(c => c.Field == "OrderDate"); - } - // Get all the Grid columns. - var columns = await Grid.GetColumns(); - // Fetch the Uid of OrderDate column. + Grid.FilterSettings.Columns.RemoveAll(c => c.Field == "OrderDate"); + + var columns = await Grid.GetColumnsAsync(); string fUid = columns[2].Uid; + Grid.FilterSettings.Columns.Add(new GridFilterColumn { Field = "OrderDate", @@ -1370,19 +1383,41 @@ In this configuration, the `SfDateRangePicker` is rendered in the filter templat Field = "OrderDate", Operator = Syncfusion.Blazor.Operator.LessThanOrEqual, Predicate = "and", - Value = EndDate.AddDays(1).AddSeconds(-1), + Value = EndDate?.AddDays(1).AddSeconds(-1), Uid = fUid }); + Grid.Refresh(); } + else if (args.ColumnName == "OrderDate" && args.FilterPredicates == null) + { + StartDate = null; + EndDate = null; + + } + + } + + public void FilterDialogOpeningHandler(FilterDialogOpeningEventArgs args) + { + if (args.ColumnName == "OrderDate") + { + IsOrderDateCssEnabled = true; + } + else + { + IsOrderDateCssEnabled = false; + } } - public void ValueChangeHandler(RangePickerEventArgs args) + + public void ValueChangeHandler(RangePickerEventArgs args) { StartDate = args.StartDate; EndDate = args.EndDate; } } + {% endhighlight %} {% highlight c# tabtitle="OrderData.cs" %} @@ -1390,7 +1425,6 @@ In this configuration, the `SfDateRangePicker` is rendered in the filter templat public class OrderData { public static List Orders = new List(); - public OrderData() { } public OrderData(int? OrderID, string CustomerID, DateTime? OrderDate, double? Freight) { @@ -1402,14 +1436,14 @@ public class OrderData public static List GetAllRecords() { - if (Orders.Count() == 0) + if (Orders.Count == 0) { int OrderID = 10248; int j = 1; for (int i = 1; i < 7; i++) { Orders.Add(new OrderData(OrderID + 1, "VINET", DateTime.Now.AddDays(-j), 32.38)); - Orders.Add(new OrderData(OrderID + 2, "TOMSP", DateTime.Now.AddDays(-j-1), 11.61)); + Orders.Add(new OrderData(OrderID + 2, "TOMSP", DateTime.Now.AddDays(-j - 1), 11.61)); Orders.Add(new OrderData(OrderID + 3, "HANAR", DateTime.Now.AddDays(-j - 2), 65.83)); Orders.Add(new OrderData(OrderID + 4, "VICTE", DateTime.Now.AddDays(-j - 3), 45.78)); Orders.Add(new OrderData(OrderID + 5, "SUPRD", DateTime.Now.AddDays(-j - 4), 98.6)); @@ -1433,7 +1467,7 @@ public class OrderData {% endhighlight %} {% endtabs %} -{% previewsample "https://blazorplayground.syncfusion.com/embed/rjLJCLClyfCMmKmA?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %} +{% previewsample "https://blazorplayground.syncfusion.com/embed/VjhSsLixJHGezNcW?appbar=true&editor=true&result=true&errorlist=true&theme=bootstrap5" %} ## Troubleshoot filter menu operator issue