如何使用Blazor和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.

微软最近宣布了一个名为Blazor的新.NET Web框架的发布。 在本文中,我们将在实体框架核心的帮助下使用Blazor创建一个Web应用程序。 我们将创建一个示例员工记录管理系统并在其上执行CRUD操作。

先决条件 (Prerequisites)

  • Install .NET Core 2.1 Preview 2 SDK from here

    此处安装.NET Core 2.1 Preview 2 SDK

  • Install a preview of Visual Studio 2017 v15.7 from here

    此处安装Visual Studio 2017 v15.7的预览

  • Install ASP.NET Core Blazor Language Services extension from here

    此处安装ASP.NET Core Blazor语言服务扩展

  • SQL Server 2012 or above

    SQL Server 2012或以上

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

Visual Studio 2017 v15.7以下的版本不支持Blazor框架。

Before proceeding further, I suggest you read my previous article on getting started with Blazor.

在继续进行之前,建议您阅读我以前的有关Blazor入门的文章

源代码 (Source code)

Also, I would recommend that you get the source code from Github before getting started.

另外,我建议您在开始之前从Github获取源代码。

创建表 (Creating the table)

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:

打开SQL Server并使用以下脚本创建tblEmployee表:

Create table tblEmployee(            EmployeeId int IDENTITY(1,1) NOT NULL,            Name varchar(20) NOT NULL,            City varchar(20) NOT NULL,            Department varchar(20) NOT NULL,            Gender varchar(6) NOT NULL        )

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

现在,让我们继续创建我们的Web应用程序。

创建Blazor Web应用程序 (Create the Blazor web application)

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

打开Visual Studio,然后选择“文件>>新建>>项目”。

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

选择项目后,将打开“新建项目”对话框。 从左侧面板的Visual C#菜单中选择.NET Core。

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

然后,从可用的项目类型中选择“ ASP.NET Core Web应用程序”。 将项目名称命名为BlazorCrud 然后按确定。

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.

单击确定后,将打开一个新对话框,要求您选择项目模板。 您将在模板窗口的左上方看到两个下拉菜单。 从这些下拉列表中选择“ .NET Core”和“ ASP.NET Core 2.0”。 然后,选择“ Blazor(ASP.NET Core托管)”模板,然后按OK。

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

现在,将创建我们的Blazor解决方案。 您可以在解决方案资源管理器中观察文件夹结构,如下图所示。

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

您将看到我们在此解决方案内部创建了3个项目文件:

  1. BlazorCrud.Client — It has the client side code and contains the pages that will be rendered on the browser.

    BlazorCrud.Client —它具有客户端代码,并且包含将在浏览器中呈现的页面。
  2. BlazorCrud.Server — It has the server side code, such as DB related operations and the web API.

    BlazorCrud.Server-它具有服务器端代码,例如与DB相关的操作和Web API。
  3. BlazorCrud.Shared — It contains the shared code that can be accessed by both client and server.

    BlazorCrud.Shared —它包含可以由客户端和服务器访问的共享代码。

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.

在这里,您可以在左侧看到一个导航菜单,其中包含对我们应用程序页面的导航。 默认情况下,我们的应用程序中提供了“计数器”和“获取数据”页面。 这些默认页面不会影响我们的应用程序,但是为了本教程的缘故,我们将删除fetchdata BlazorCrud.Client / Pages的 计数器页面 夹。

将模型添加到应用程序 (Adding the model to the application)

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.

右键单击BlazorCrud.Shared项目,然后选择添加>>新建文件夹,并将其命名为较旧的模型。 我们将仅在此文件夹中添加模型类。

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:

右键单击Models文件夹,然后选择Add >> Class。 命名类Emplo 你们 e.cs. 此类将包含我们的Employee模型属性。 不, 我们的BlazorCrud。 共享项目具有以下结构:

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

打开Employee.cs并将以下代码放入其中:

using System;  using System.Collections.Generic;  using System.ComponentModel.DataAnnotations;  using System.Text;    namespace BlazorCrud.Shared.Models  {      public class Employee      {          public int EmployeeId { get; set; }          [Required]          public string Name { get; set; }          [Required]          public string Gender { get; set; }          [Required]          public string Department { get; set; }          [Required]          public string City { get; set; }      }  }

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

这样就创建了我们的模型。 现在,我们将创建数据访问层。

为应用程序创建数据访问层 (Creating the data access layer for the application)

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.

右键单击BlazorCrud.Server项目,然后选择添加>>新建文件夹,并将其命名为较旧的数据访问。 我们将添加类以仅在此文件夹内处理与数据库相关的操作。

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:

右键单击DataAccess文件夹,然后选择添加>>类。 命名类EmployeeCont t.cs. 这是我们的Entity Framework DB上下文类,它使我们可以与数据库进行交互。 打开EmployeeCont e xt.cs并将以下代码放入其中:

using BlazorCrud.Shared.Models;  using Microsoft.EntityFrameworkCore;  using System;  using System.Collections.Generic;  using System.Linq;  using System.Threading.Tasks;    namespace BlazorCrud.Server.DataAccess  {      public class EmployeeContext : DbContext      {          public virtual DbSet<Employee> tblEmployee { get; set; }            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)          {              if (!optionsBuilder.IsConfigured)              {                  optionsBuilder.UseSqlServer(@"Put Your Connection string here");              }          }      }  }

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:

DataAccess文件夹中再添加一个类,并将其命名为EmployeeDataAccessLayer.cs 此类将处理与CRUD相关的数据库操作。 打开EmployeeDataAccessLayer.cs 并将以下代码放入其中:

using BlazorCrud.Shared.Models;  using Microsoft.EntityFrameworkCore;  using System;  using System.Collections.Generic;  using System.Linq;  using System.Threading.Tasks;    namespace BlazorCrud.Server.DataAccess  {      public class EmployeeDataAccessLayer      {          EmployeeContext db = new EmployeeContext();            //To Get all employees details           public IEnumerable<Employee> GetAllEmployees()          {              try              {                  return db.tblEmployee.ToList();              }              catch              {                  throw;              }          }            //To Add new employee record             public void AddEmployee(Employee employee)          {              try              {                  db.tblEmployee.Add(employee);                  db.SaveChanges();              }              catch              {                  throw;              }          }            //To Update the records of a particluar employee            public void UpdateEmployee(Employee employee)          {              try              {                  db.Entry(employee).State = EntityState.Modified;                  db.SaveChanges();              }              catch              {                  throw;              }          }            //Get the details of a particular employee            public Employee GetEmployeeData(int id)          {              try              {                  Employee employee = db.tblEmployee.Find(id);                  return employee;              }              catch              {                  throw;              }          }            //To Delete the record of a particular employee            public void DeleteEmployee(int id)          {              try              {                  Employee emp = db.tblEmployee.Find(id);                  db.tblEmployee.Remove(emp);                  db.SaveChanges();              }              catch              {                  throw;              }          }      }  }

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

现在我们的数据访问层已经完成。 接下来,我们将继续创建我们的Web API控制器。

将Web API控制器添加到应用程序 (Adding the web API controller to the application)

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.

右键单击BlazorCrud.Server / Controllers文件夹,然后选择添加>>新建项。 “添加新项”对话框将打开。 从左侧面板中选择一个 SP.NET,然后从模板面板中选择“ API控制器类”,并将命名为EmployeeController.cs 。 按确定。

This will create our API EmployeeController class.

这将创建我们的API EmployeeController 类。

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

我们将调用EmployeeDataAccessLayer的方法 类以获取数据并将数据传递给客户端。

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

打开EmployeeController.cs 文件,并将以下代码放入其中:

using System;  using System.Collections.Generic;  using System.Linq;  using System.Threading.Tasks;  using BlazorCrud.Server.DataAccess;  using BlazorCrud.Shared.Models;  using Microsoft.AspNetCore.Mvc;    namespace BlazorCrud.Server.Controllers  {      public class EmployeeController : Controller      {          EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();            [HttpGet]          [Route("api/Employee/Index")]          public IEnumerable<Employee> Index()          {              return objemployee.GetAllEmployees();          }            [HttpPost]          [Route("api/Employee/Create")]          public void Create([FromBody] Employee employee)          {              if (ModelState.IsValid)                  objemployee.AddEmployee(employee);          }            [HttpGet]          [Route("api/Employee/Details/{id}")]          public Employee Details(int id)          {                return objemployee.GetEmployeeData(id);          }            [HttpPut]          [Route("api/Employee/Edit")]          public void Edit([FromBody]Employee employee)          {              if (ModelState.IsValid)                  objemployee.UpdateEmployee(employee);          }            [HttpDelete]          [Route("api/Employee/Delete/{id}")]          public void Delete(int id)          {              objemployee.DeleteEmployee(id);          }      }  }

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

至此,我们的BlazorCrud.Server项目具有以下结构:

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

我们已经完成了后端逻辑。 因此,我们现在开始对客户端进行编码。

将Razor View添加到应用程序 (Adding Razor View to the application)

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.

右键单击BlazorCrud.Client / Pages文件夹,然后选择添加>>新建项目。 将打开“添加新项”对话框,从左侧面板中选择“ Web”,然后从模板面板中选择“ Razor View”,并将其命名为FetchEmployee。 c shtml。

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.

这将添加一个FetchEmployee.cshtml 页面到我们的BlazorCrud.Client / Pages文件夹。 同样,再添加3个页面: AddEmployee.cshtml EditEmployee.cshtmlDeleteEmployee.cshtml

Now our BlazorCrud.Client project has the following structure:

现在,我们的BlazorCrud.Client项目具有以下结构:

Let’s add code to these pages.

让我们向这些页面添加代码。

FetchEmployee.cshtml (FetchEmployee.cshtml)

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:

打开FetchEmployee.cshtml并将以下代码放入其中:

@using BlazorCrud.Shared.Models@page "/fetchemployee"@inject HttpClient Http<h1>Employee Data</h1><p>This component demonstrates fetching Employee data from the server.</p><p>    <a href="/addemployee">Create New</a></p>@if (empList == null){    <p><em>Loading...</em></p>}else{    <table class='table'>        <thead>            <tr>                <th>ID</th>                <th>Name</th>                <th>Gender</th>                <th>Department</th>                <th>City</th>            </tr>        </thead>        <tbody>            @foreach (var emp in empList)            {                <tr>                    <td>@emp.EmployeeId</td>                    <td>@emp.Name</td>                    <td>@emp.Gender</td>                    <td>@emp.Department</td>                    <td>@emp.City</td>                    <td>                        <a href='/editemployee/@emp.EmployeeId'>Edit</a>  |                        <a href='/delete/@emp.EmployeeId'>Delete</a>                    </td>                </tr>            }        </tbody>    </table>}@functions {Employee[] empList;protected override async Task OnInitAsync(){    empList = await Http.GetJsonAsync<Employee[]>    ("/api/Employee/Index");}}

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.

让我们了解这段代码。 在顶部,我们包括BlazorEFApp.Shared.Models命名空间,以便我们可以在此页面中使用Employee模型类。

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.

我们正在使用@page指令定义此页面的路由。 因此,在此应用程序中,如果我们将“ / fetchemployee”附加到基本URL,我们将被重定向到此页面。 我们还将注入HttpClient服务以启用Web API调用。

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.

然后,我们定义了HTML部分,以表格形式显示所有员工记录。 我们还为“ 编辑”和“ 删除”添加了两个操作链接,这两个链接将分别导航到EditEmployee.cshtmlDeleteEmployee.cshtml页面。

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.

在页面底部,我们有一个@functions部分,其中包含我们的业务逻辑。 我们创建了一个类型为Employee的数组变量empList ,并通过调用Web API将其填充在OnInitAsync方法中。 这将在页面加载时绑定到我们HTML表。

AddEmployee.cshtml (AddEmployee.cshtml)

This page is used to create a new employee record.

此页面用于创建新的员工记录。

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

打开AddEmployee.cshtml并将以下代码放入其中:

@using BlazorCrud.Shared.Models@page "/addemployee"@inject HttpClient Http@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper<h1>Create</h1><h3>Employee</h3><hr /><div class="row">    <div class="col-md-4">        <form>            <div class="form-group">                <label for="Name" class="control-label">Name</label>                <input for="Name" class="form-control" bind="@emp.Name" />            </div>            <div class="form-group">                <label asp-for="Gender" class="control-label">Gender</label>                <select asp-for="Gender" class="form-control" bind="@emp.Gender">                    <option value="">-- Select Gender --</option>                    <option value="Male">Male</option>                    <option value="Female">Female</option>                </select>            </div>            <div class="form-group">                <label asp-for="Department" class="control-label">Department</label>                <input asp-for="Department" class="form-control" bind="@emp.Department" />            </div>            <div class="form-group">                <label asp-for="City" class="control-label">City</label>                <input asp-for="City" class="form-control" bind="@emp.City" />            </div>            <div class="form-group">                <button type="submit" class="btn btn-default" onclick="@(async () => await CreateEmployee())">Save</button>                <button class="btn" onclick="@cancel">Cancel</button>            </div>        </form>    </div></div>@functions {Employee emp = new Employee();protected async Task CreateEmployee(){    await Http.SendJsonAsync(HttpMethod.Post, "/api/Employee/Create", emp);    UriHelper.NavigateTo("/fetchemployee");}void cancel(){    UriHelper.NavigateTo("/fetchemployee");}}

In this page the route is “/addemployee”.

在此页面中,路由为“ / 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.

我们还将注入“ Microsoft.AspNetCore.Blazor.Services.IUriHelper”服务以启用URL重定向。 HTML部分将生成一个表单以获取用户输入。 属性“ bind”用于将在文本框中输入的值绑定到Employee对象的属性。

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.

在@functions部分,我们定义了两个方法。 单击“提交”按钮将调用CreateEmployee方法,并将POST请求与Employee对象emp一起发送到我们的API。

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

取消 单击“取消”按钮将调用该方法,并将用户重定向回FetchEmployee页面。

EditEmployee.cshtml (EditEmployee.cshtml)

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

此页面用于编辑员工的详细信息。

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

打开EditEmployee.cshtml并将以下代码放入其中:

@using BlazorCrud.Shared.Models@page "/editemployee/{empID}"@inject HttpClient Http@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper<h2>Edit</h2><h4>Employees</h4><hr /><div class="row">    <div class="col-md-4">        <form>            <div class="form-group">                <label for="Name" class="control-label">Name</label>                <input for="Name" class="form-control" bind="@emp.Name" />            </div>            <div class="form-group">                <label asp-for="Gender" class="control-label">Gender</label>                <select asp-for="Gender" class="form-control" bind="@emp.Gender">                    <option value="">-- Select Gender --</option>                    <option value="Male">Male</option>                    <option value="Female">Female</option>                </select>            </div>            <div class="form-group">                <label asp-for="Department" class="control-label">Department</label>                <input asp-for="Department" class="form-control" bind="@emp.Department" />            </div>            <div class=" form-group">                <label asp-for="City" class="control-label">City</label>                <input asp-for="City" class="form-control" bind="@emp.City" />            </div>            <div class="form-group">                <input type="submit" value="Save" onclick="@(async () => await UpdateEmployee())" class="btn btn-default" />                <input type="submit" value="Cancel" onclick="@cancel" class="btn" />            </div>        </form>    </div></div>@functions {[Parameter]string empID { get; set; }Employee emp = new Employee();protected override async Task OnInitAsync(){    emp = await Http.GetJsonAsync<Employee>("/api/Employee/Details/" + Convert.ToInt32(empID));}protected async Task UpdateEmployee(){    await Http.SendJsonAsync(HttpMethod.Put, "api/Employee/Edit", emp);    UriHelper.NavigateTo("/fetchemployee");}void cancel(){    UriHelper.NavigateTo("/fetchemployee");}}

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.

在此页面中,我们将路由定义为“ / editemployee / {empID}”。 empID是在@functions部分中声明的string类型的URL参数。 我们将使用[Parameter]属性将变量标记为参数。 要导航到此页面,我们需要在URL中传递员工ID,该ID将在empID中捕获 变量。

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.

如果不使用[Parameter]属性标记变量,则会出现以下错误:“类型为'BlazorCrud.Client.Pages.EditEmployee'的对象具有与名称'empID'相匹配的属性,但没有[ ParameterAttribute]。” 这将不允许empID绑定到参数中传递的员工ID值。

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.

HTML部分类似于AddEmployee.cshtml页面的部分。 属性“ bind”用于双向绑定,即将文本框值绑定到员工对象属性,反之亦然。

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.

里面的@functions部分,我们获取的OnInitAsync雇员记录 基于传入参数的employeeID的方法。 这将绑定到页面加载本身上表单中的字段。

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.

UpdateEmployee方法将PUT请求与Employee对象emp一起发送到我们的API。 单击“取消”按钮将调用Cancel方法,并将用户重定向回FetchEmployee页面。

DeleteEmployee.cshtml (DeleteEmployee.cshtml)

This page will be used to delete an employee record.

此页面将用于删除员工记录。

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

打开DeleteEmployee.cshtml并将以下代码放入其中:

@using BlazorCrud.Shared.Models@page "/delete/{empID}"@inject HttpClient Http@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper<h2>Delete</h2><h3>Are you sure you want to delete employee with id : @empID</h3><br /><div class="col-md-4">    <table class="table">        <tr>            <td>Name</td>            <td>@emp.Name</td>        </tr>        <tr>            <td>Gender</td>            <td>@emp.Gender</td>        </tr>        <tr>            <td>Department</td>            <td>@emp.Department</td>        </tr>        <tr>            <td>City</td>            <td>@emp.City</td>        </tr>    </table>    <div class="form-group">        <input type="submit" value="Delete" onclick="@(async () => await Delete())" class="btn btn-default" />        <input type="submit" value="Cancel" onclick="@cancel" class="btn" />    </div></div>@functions {[Parameter]string empID { get; set; }Employee emp = new Employee();protected override async Task OnInitAsync(){    emp = await Http.GetJsonAsync<Employee>    ("/api/Employee/Details/" + Convert.ToInt32(empID));}protected async Task Delete(){    await Http.DeleteAsync("api/Employee/Delete/" + Convert.ToInt32(empID));    UriHelper.NavigateTo("/fetchemployee");}void cancel(){    UriHelper.NavigateTo("/fetchemployee");}}

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.

HTML部分将显示员工数据,并要求用户确认删除员工记录。

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.

在@functions部分中,我们在OnInitAsync中获取员工记录 基于传入参数的employeeID的方法。 这将在页面加载时显示员工记录。

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.

单击“删除”按钮将调用Delete方法,这将向我们的API发送删除请求以及要删除的员工的员工ID。 成功删除后,用户将导航回FetchEmployee页面。

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:

最后一步是为我们的应用程序定义导航菜单。 打开BlazorCrud.Client / Shared / NavMenu.cshtml文件,并将以下代码放入其中:

<div class="top-row pl-4 navbar navbar-dark">    <a class="navbar-brand" href="/">BlazorCrud</a>    <button class="navbar-toggler" onclick=@ToggleNavMenu>        <span class="navbar-toggler-icon"></span>    </button></div><div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>    <ul class="nav flex-column">        <li class="nav-item px-3">            <NavLink class="nav-link" href="/" Match=NavLinkMatch.All>                <span class="oi oi-home" aria-hidden="true"></span> Home            </NavLink>        </li>        <li class="nav-item px-3">            <NavLink class="nav-link" href="/fetchemployee">                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch employee            </NavLink>        </li>    </ul></div>@functions {bool collapseNavMenu = true;void ToggleNavMenu(){    collapseNavMenu = !collapseNavMenu;}}

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

就是这样。 我们使用Blazor和Entity Framework Core创建了第一个ASP.NET Core应用程序。

执行演示 (Execution demo)

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.

在导航菜单中,点击提取员工 。 它将重定向到FetchEmployee视图,并将在页面上显示所有员工数据。 请注意,正如我们使用@page指令定义的那样,URL后面附加了“ / fetchemployee”。

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:

单击CreateNew导航到AddEmployee视图。 请注意,正如我们使用@page指令定义的那样,URL后面附加了“ / addemployee”。 如下图所示添加新的Employee记录:

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.

在所有字段中插入数据后,单击“保存”按钮。 将创建新的员工记录,并将您重定向到FetchEmployee视图,该视图将显示所有员工的记录。 在这里,我们还可以看到与每个记录相对应的操作方法“ 编辑”和“ 删除”

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.

如果要编辑现有的员工记录,只需单击“ 编辑”操作链接。 它将打开“ 编辑”视图,如下所示。 在这里我们可以更改员工数据。 请注意,我们已经在URL参数中传递了员工ID。

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:

在这里,我们已将员工Swati市从新德里更改为金奈。 单击“保存”返回到FetchEmployee视图,以查看更新的更改,如下图所示:

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.

现在,我们将对名为Rahul的员工执行Delete操作。 单击删除操作链接,这将打开“ 删除”视图,要求您确认删除。 请注意,我们已经在URL参数中传递了员工ID。

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.

单击删除按钮后,它将删除员工记录,并将我们重定向到FetchEmployee视图。 在这里,我们可以看到名为Rahul的员工已从我们的记录中删除。

托管应用 (Hosting the application)

To learn how to host a Blazor application using IIS, refer to Deploying a Blazor Application on IIS.

要了解如何使用IIS托管Blazor应用程序,请参阅在IIS上部署Blazor应用程序

也可以看看 (See Also)

结论 (Conclusion)

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.

我们已经在Visual Studio 2017和SQL Server 2012的帮助下使用新的Web框架Blazor和Entity Framework Core创建了ASP.NET Core应用程序。我们还对应用程序执行了CRUD操作。

You can also fork this application on Github. Try this new framework and let me know what you think of it in the comments section below.

您也可以在Github上分叉此应用程序。 试试这个新框架,并在下面的评论部分中告诉我您的想法。

Get my book Blazor Quick Start Guide to learn more about Blazor.

获取我的书《 Blazor快速入门指南》,以了解有关Blazor的更多信息。

You can also find this article at C# Corner.

您也可以在C#Corner上找到此文章。

You can check my other articles on ASP .NET Core here

您可以在此处查看有关ASP .NET Core的其他文章

Originally published at https://ankitsharmablogs.com/

最初发布在https://ankitsharmablogs.com/

翻译自: https://www.freecodecamp.org/news/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值