Can I Buy Happiness?

Is my happiness contingent upon accumulating more wealth and possessions in a world that often equates happiness with material gain. There have been moments when the allure of wealth and possessions…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




How to create an application using Blazor and Entity Framework Core

Microsoft has recently announced the release of a new .NET web framework called Blazor. In this article, we are going to create a web application using Blazor with the help of Entity Framework Core. We will be creating a sample Employee Record Management System and perform CRUD operations on it.

The Blazor framework is not supported by versions below Visual Studio 2017 v15.7.

We will be using a DB table to store all the records of the employees.

Open SQL Server and use the following script to create the tblEmployee table:

Now, let’s move on to create our web application.

Open Visual Studio and select File >> New >> Project.

After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel.

Then, select “ASP.NET Core Web Application” from the available project types. Put the name of the project as BlazorCrud and press OK.

After clicking OK, a new dialog will open asking you to select the project template. You will see two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Blazor (ASP .NET Core hosted)” template and press OK.

Now, our Blazor solution will be created. You can observe the folder structure in Solution Explorer as shown in the below image.

You will see that we have 3 project files created inside this solution:

Execute the program. It will open the browser and you will see a page similar to the one shown below.

Here you can see a navigation menu on the left side, which contains the navigation to the pages in our application. By default, we have “Counter” and “Fetch Data” pages provided in our application. These default pages will not affect our application, but for the sake of this tutorial, we will delete the fetchdata and counter pages from BlazorCrud.Client/Pages folder.

Right click on BlazorCrud.Shared project and then select Add >> New Folder and name the folder Models. We will be adding our model class in this folder only.

Right click on the Models folder and select Add >> Class. Name your class Employee.cs. This class will contain our Employee model properties. Now our BlazorCrud.Shared project has the following structure:

Open Employee.cs and put the following code in it:

And so our model has been created. Now we will create our data access layer.

Right click on BlazorCrud.Server project and then select Add >> New Folder and name the folder DataAccess. We will be adding our classes to handle database-related operations inside this folder only.

Right click on the DataAccess folder and select Add >> Class. Name your class EmployeeContext.cs. This is our Entity Framework DB context class that allows us to interact with the database. Open EmployeeContext.cs and put the following code into it:

Do not forget to put in your own connection string.

Add one more class to DataAccess folder and name it EmployeeDataAccessLayer.cs. This class will handle our CRUD related DB operations. Open EmployeeDataAccessLayer.cs and put the following code into it:

Now our data access layer is complete. Next, we will proceed to create our web API Controller.

Right click on BlazorCrud.Server/Controllers folder and select Add >> New Item. An “Add New Item” dialog box will open. Select ASP.NET from the left panel, then select “API Controller Class” from the templates panel and name it EmployeeController.cs. Press OK.

This will create our API EmployeeController class.

We will call the methods of the EmployeeDataAccessLayer class to fetch data and pass on the data to the client side.

Open the EmployeeController.cs file and put the following code into it:

At this point, our BlazorCrud.Server project has the following structure:

We are done with our backend logic. So we will now proceed to code our client side.

Right click on the BlazorCrud.Client/Pages folder and then select Add >> New Item. An “Add New Item” dialog box will open, select Web from the left panel, then select “Razor View” from the templates panel and name it FetchEmployee.cshtml.

This will add a FetchEmployee.cshtml page to our BlazorCrud.Client/Pages folder. Similarly, add 3 more pages: AddEmployee.cshtml, EditEmployee.cshtml, and DeleteEmployee.cshtml.

Now our BlazorCrud.Client project has the following structure:

Let’s add code to these pages.

This page will display all the employee records present in the database. Additionally, we will also provide the action methods Edit and Delete on each record.

Open FetchEmployee.cshtml and put the following code in it:

Let’s understand this code. At the top, we have included the BlazorEFApp.Shared.Models namespace so that we can use our Employee model class in this page.

We are defining the route of this page using the @page directive. So, in this application, if we append “/fetchemployee” to the base URL, we will be redirected to this page. We are also injecting HttpClient service to enable the web API call.

Then we have defined the HTML part to display all the employees records in a tabular manner. We have also added two action links for Edit and Delete which will navigate to the EditEmployee.cshtml and DeleteEmployee.cshtml pages, respectively.

At the bottom of the page, we have a @functions section which contains our business logic. We have created an array variable empList of type Employee, and we and populate it inside OnInitAsync method by calling our web API. This will bind to our HTML table on the page load.

This page is used to create a new employee record.

Open AddEmployee.cshtml and put the following code into it:

In this page the route is “/addemployee”.

We are also injecting the “Microsoft.AspNetCore.Blazor.Services.IUriHelper” service to enable URL redirection. The HTML part will generate a form to get input from the user. The attribute “bind” is used to bind the value entered in the textbox to the properties of the Employee object.

In the @functions section, we have defined two methods. The method CreateEmployee will be invoked on clicking the “Submit” button and will send a POST request to our API along with the Employee object emp.

The Cancel method will be invoked on clicking the cancel button and will redirect the user back to the FetchEmployee page.

This page is used to edit the details of an employee.

Open EditEmployee.cshtml and put the following code into it:

In this page we have defined the route as “/editemployee/{empID}”. empID is an URL parameter of type string declared in the @functions section. We will use the [Parameter] attribute to mark the variable as a parameter. To navigate to this page, we need to pass the employee id in the URL which will be captured in the empID variable.

If we do not mark the variable with the [Parameter] attribute, we will get the following error: “Object of type ‘BlazorCrud.Client.Pages.EditEmployee’ has a property matching the name ’empID’, but it does not have [ParameterAttribute] applied.” This will not allow empID to bind to the employee id value passed in the parameter.

The HTML part is similar to that of the AddEmployee.cshtml page. The attribute “bind” is used for two-way binding, that is binding the textbox values to employee object properties, and vice versa.

Inside the @functions section, we are fetching the employee records in the OnInitAsync method based on the employeeID passed in the parameter. This will bind to the fields in the form on page load itself.

The UpdateEmployee method will send a PUT request to our API along with the Employee object emp. The Cancel method will be invoked on clicking the cancel button and will redirect the user back to the FetchEmployee page.

This page will be used to delete an employee record.

Open DeleteEmployee.cshtml and put the following code into it:

The route for this page is also parameterized, since we are fetching the record of the employee on page load.

The HTML part will display the employee data and ask the user for confirmation to delete the employee record.

Inside the @functions section, we are fetching the employee records inthe OnInitAsync method based on the employeeID passed in the parameter. This will display the employee records as the page loads.

The Delete method will be invoked on clicking the “Delete” button, which will send a delete request to our API along with the employee ID of the employee to be deleted. On successful deletion, the user will be navigated back to the FetchEmployee page.

The last step is to define the navigation menu for our application. Open the BlazorCrud.Client/Shared/ NavMenu.cshtml file and put the following code in it:

And that’s it. We have created our first ASP.NET Core application using Blazor and Entity Framework Core.

Launch the application.

A web page will open as shown in the image below. The navigation menu on the left will show the navigation link for the Home and Fetch Employee pages.

Click on Fetch employee in the navigation menu. It will redirect to the FetchEmployee view and will display all the employee data on the page. Notice that the URL has “/fetchemployee” appended to it, as we have defined it using the @page directive.

Since we have not added any data, it is empty.

Click on CreateNew to navigate to AddEmployee view. Notice the URL has “/addemployee” appended to it, as we have defined it using the @page directive. Add a new Employee record as shown in the image below:

After inserting data in all the fields, click on the “Save” button. The new employee record will be created, and you will be redirected to the FetchEmployee view, which will display records of all the employees. Here, we can also see the action methods Edit and Delete corresponding to each record.

If we want to edit an existing employee record, we just click on the Edit action link. It will open the Edit view as shown below. Here we can change the employee data. Notice that we have passed the employee id in the URL parameter.

Here we have changed the City of employee Swati from New Delhi to Chennai. Click on “Save” to return to the FetchEmployee view to see the updated changes as highlighted in the image below:

Now, we will perform the Delete operation on the employee named Rahul. Click on the Delete action link which will open the Delete view asking for a confirmation to delete. Notice that we have passed the employee id in the URL parameter.

Once we click on the Delete button, it will delete the employee record and we will be redirected to the FetchEmployee view. Here, we can see that the employee with name Rahul has been removed from our record.

We have created an ASP.NET Core application using the new web framework Blazor and Entity Framework Core with the help of Visual Studio 2017 and SQL Server 2012. We have also performed CRUD operations on our application.

Add a comment

Related posts:

My Mucous Mental Disorder

I recently weaned myself off bupropion, which is commonly prescribed as a smoking cessation aid. It’s not that I was trying to quit cigarettes; I’ve been smoke-free for many years. I’d requested my…

Newsfeed for Crowd Supply projects

I just created v1 of a “RSS feed” for Crowd Supply, which is basically the best site for crowdfunded maker/hacker projects. Crowd Supply has a weekly email and nothing else- no forums or feeds. I…

My Best Friend

All that glitters isn’t gold, especially when the weather is cold, and I forget to let Sam out to use the bathroom. They also say, “When you lie down with dogs, you wake up with fleas.” Maybe that…