使用EntityFramework Core和Enums作为字符串的ASP.NET Core Razor页面——第二部分

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mzl87/article/details/85312335

目录

介绍

使用代码

完整的客户CRUD

客户创造

显示客户详情

编辑客户信息

删除客户记录


完整的初始化CRUD页面

介绍

这是一篇由多部分组成的文章的第二部分,演示了通过EntityFramework Core 2.1EF)将Cenum值映射到数据库表中的string值。它解决了enum与应用程序实体的一对多和多对多关系中的值映射问题。它在ASP.NET Core Razor Page应用程序的上下文中执行此操作。

EF是对象关系映射器(ORM)。在诸如此示例的应用程序中,有两个世界。一个是在C#中作为对象模型存在的对象世界。另一个是存在于关系数据库中的关系世界,如Microsoft SQL Server。这两个世界并不一致。ORM的功能,如EntityFramework,就是这两个世界之间的桥梁,并促进它们之间的数据传输。

第一部分:我们创建了初始对象模型,实体框架数据上下文和数据库,并显示了第一个客户Razor页面。这是所有已定义客户的客户CRUD的读取功能。

在第二部分中,我们将完成并测试客户CRUD Razor页面:

  • 实施并测试客户创建的Razor页面,Customers\Create.cshtml。这是CustomerCRUD Create功能。
  • Customers\Details.cshtml Razor页面中实现Customer详细信息的显示,这是由其CustomerId属性标识的单个Customer函数的实现的Read功能。
  • Customers\Edit.cshtml Razor页面中实现Customer属性的编辑,Customer CRUD Update功能。
  • 最后,在Customers\Delete.cshtml Razor Page中实现Customer CRUD Delete功能。

使用代码

完整的客户CRUD

在这一点上,我们已经完成了Customers表格的基本阅读。现在,我们将完成剩余的CustomerCRUD功能。

客户创造

Pages\Customers\Create文件处理数据库中的Customer记录的创建。

生成的Pages\Customers\Create.cshtml

@page
@model QuantumWeb.Pages.Customers.CreateModel

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<h4>Customer</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Customer.CustomerName" class="control-label"></label>
                <input asp-for="Customer.CustomerName" class="form-control" />
                <span asp-validation-for="Customer.CustomerName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Customer.CustomerContact" class="control-label"></label>
                <input asp-for="Customer.CustomerContact" class="form-control" />
                <span asp-validation-for="Customer.CustomerContact" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Customer.CustomerPhone" class="control-label"></label>
                <input asp-for="Customer.CustomerPhone" class="form-control" />
                <span asp-validation-for="Customer.CustomerPhone" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Customer.CustomerEmail" class="control-label"></label>
                <input asp-for="Customer.CustomerEmail" class="form-control" />
                <span asp-validation-for="Customer.CustomerEmail" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

此文件包含用于POST用户输入服务器的<form>元素。

修改了Pages\Customers\Create.cshtml.cs

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuantumWeb.Data;
using QuantumWeb.Model;

namespace QuantumWeb.Pages.Customers
{
    public class CreateModel : PageModel
    {
        private readonly QuantumDbContext _context;

        public CreateModel(QuantumDbContext context)
        {
            _context = context;
        } // end public CreateModel(QuantumDbContext context)

        public IActionResult OnGet()
        {
            return Page();
        } // end public IActionResult OnGet()

        [BindProperty]
        public Customer Customer { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Customer.Add(Customer);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        } // end public async Task<IActionResult> OnPostAsync()

    } // end public class CreateModel : PageModel

} // end namespace QuantumWeb.Pages.Customers

人们可以通过单击在Customers页面上的 Create New链接到达Customers/Create

QuantumWeb应用程序客户页面:https//localhost: 44306/Customers

https://img-blog.csdnimg.cn/20181227225230687

“ Customer Create页面上并单击Create输入第一个Customer数据。

QuantumWeb应用程序客户页面:https//localhost: 44306/Customers/Create

https://www.codeproject.com/KB/dotnet/1264283/CustCreate-Page-02.jpg

QuantumWeb应用程序客户页面:https//localhost: 44306/Customers拥有第一位客户

https://www.codeproject.com/KB/dotnet/1264283/FirstCustDisplay-01-1.jpg

再添加两个后Customers,我们显示Customer页面。

QuantumWeb应用程序客户页面:https//localhost: 44306/Customers——3个客户

https://www.codeproject.com/KB/dotnet/1264283/Show-3-Cust-02.jpg

我们可以通过点击“详细信息”链接显示customer详细信息,聚烯烃加工公司。接下来列出Customers\Details.cshtmlCustomers\Details.cshtml.cs文件。

显示客户详情

生成的Pages\Customers\Details.cshtml

@page
@model QuantumWeb.Pages.Customers.DetailsModel

@{
    ViewData["Title"] = "Details";
}

<h2>Details</h2>

<div>
    <h4>Customer</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerContact)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerContact)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerPhone)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerPhone)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerEmail)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerEmail)
        </dd>
    </dl>
</div>
<div>
    <a asp-page="./Edit" asp-route-id="@Model.Customer.CustomerId">Edit</a> |
    <a asp-page="./Index">Back to List</a>
</div>

修改了Pages\Customers\Details.cshtml.cs

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using QuantumWeb.Data;
using QuantumWeb.Model;

namespace QuantumWeb.Pages.Customers
{
    public class DetailsModel : PageModel
    {
        private readonly QuantumDbContext _context;

        public DetailsModel(QuantumDbContext context)
        {
            _context = context;
        } // end public DetailsModel(QuantumDbContext context)

        public Customer Customer { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            } // end if (id == null)

            Customer = await _context.Customer.FirstOrDefaultAsync(m => m.CustomerId == id);

            if (Customer == null)
            {
                return NotFound();
            } // endif (Customer == null)
            return Page();
        } // end public async Task<IActionResult> OnGetAsync(int? id)

    } // end public class DetailsModel : PageModel

} // end namespace QuantumWeb.Pages.Customers

QuantumWeb应用程序客户详细信息页面: https//localhost: 44306/Customers/Details?id=2

https://www.codeproject.com/KB/dotnet/1264283/CustId-2-Details-01.jpg

QuantumWeb应用程序客户页面:https//localhost:44306/Customers——3个客户

https://img-blog.csdnimg.cn/20181227225230729

我们可以通过点击“ 编辑 ”链接来为customer编辑 Pascagoula Petrochemicals 的记录。接下来列出Customers\Edit.cshtmlCustomers\Edit.cshtml.cs文件。

编辑客户信息

生成的Pages\Customers\Edit.cshtml

@page
@model QuantumWeb.Pages.Customers.EditModel

@{
    ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

<h4>Customer</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Customer.CustomerId" />
            <div class="form-group">
                <label asp-for="Customer.CustomerName" class="control-label"></label>
                <input asp-for="Customer.CustomerName" class="form-control" />
                <span asp-validation-for="Customer.CustomerName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Customer.CustomerContact" class="control-label"></label>
                <input asp-for="Customer.CustomerContact" class="form-control" />
                <span asp-validation-for="Customer.CustomerContact" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Customer.CustomerPhone" class="control-label"></label>
                <input asp-for="Customer.CustomerPhone" class="form-control" />
                <span asp-validation-for="Customer.CustomerPhone" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Customer.CustomerEmail" class="control-label"></label>
                <input asp-for="Customer.CustomerEmail" class="form-control" />
                <span asp-validation-for="Customer.CustomerEmail" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="./Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

修改了Pages\Customers\Edit.cshtml.cs

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using QuantumWeb.Data;
using QuantumWeb.Model;

namespace QuantumWeb.Pages.Customers
{
    public class EditModel : PageModel
    {
        private readonly QuantumDbContext _context;

        public EditModel(QuantumDbContext context)
        {
            _context = context;
        } // end public EditModel(QuantumDbContext context)

        [BindProperty]
        public Customer Customer { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            } // endif (id == null)

            Customer = await _context.Customer.FirstOrDefaultAsync(m => m.CustomerId == id);

            if (Customer == null)
            {
                return NotFound();
            } // endif (Customer == null)
            return Page();
        } // end public async Task<IActionResult> OnGetAsync(int? id)

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            } // endif (!ModelState.IsValid)

            _context.Attach(Customer).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            } // end try
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(Customer.CustomerId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                } // endif (!CustomerExists(Customer.CustomerId))
            } // end catch (DbUpdateConcurrencyException)

            return RedirectToPage("./Index");
        } // end public async Task<IActionResult> OnPostAsync()

        private bool CustomerExists(int id)
        {
            return _context.Customer.Any(e => e.CustomerId == id);
        } // end private bool CustomerExists(int id)

    } // end public class EditModel : PageModel

} // end namespace QuantumWeb.Pages.Customers

QuantumWeb应用程序客户编辑页面:https/localhost:44306/Customers/Edit?id=3

https://www.codeproject.com/KB/dotnet/1264283/CustId-3-Edit-01.jpg

我们更改所选的Customer值并保存更改。

QuantumWeb应用程序客户页面:https//localhost:44306/Customers——已更改客户

https://www.codeproject.com/KB/dotnet/1264283/Show-3-Cust-04.jpg

我们看到了编辑过的值。现在,我们通过单击“ 删除 ”链接删除Customer 。接下来列出Customers\Delete.cshtmlCustomers\Delete.cshtml.cs文件。

删除客户记录

生成的Pages\Customers\Delete.cshtml

@page
@model QuantumWeb.Pages.Customers.DeleteModel

@{
    ViewData["Title"] = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Customer</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerContact)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerContact)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerPhone)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerPhone)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Customer.CustomerEmail)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Customer.CustomerEmail)
        </dd>
    </dl>
   
    <form method="post">
        <input type="hidden" asp-for="Customer.CustomerId" />
        <input type="submit" value="Delete" class="btn btn-default" /> |
        <a asp-page="./Index">Back to List</a>
    </form>
</div>

修改过Pages\Customers\Delete.cshtml.cs

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using QuantumWeb.Data;
using QuantumWeb.Model;

namespace QuantumWeb.Pages.Customers
{
    public class DeleteModel : PageModel
    {
        private readonly QuantumDbContext _context;

        public DeleteModel(QuantumDbContext context)
        {
            _context = context;
        } // end public DeleteModel(QuantumDbContext context)

        [BindProperty]
        public Customer Customer { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            } // endif (id == null)

            Customer = await _context.Customer.FirstOrDefaultAsync(m => m.CustomerId == id);

            if (Customer == null)
            {
                return NotFound();
            } // endif (Customer == null)
            return Page();
        } // end public async Task<IActionResult> OnGetAsync(int? id)

        public async Task<IActionResult> OnPostAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            } // endif (id == null)

            Customer = await _context.Customer.FindAsync(id);

            if (Customer != null)
            {
                _context.Customer.Remove(Customer);
                await _context.SaveChangesAsync();
            } // endif (Customer != null)

            return RedirectToPage("./Index");
        } // end public async Task<IActionResult> OnPostAsync(int? id)

    } // end public class DeleteModel : PageModel

} // end namespace QuantumWeb.Pages.Customers

QuantumWeb应用程序客户删除页面:https//localhost:44306/Customers/Delete?id=3

https://www.codeproject.com/KB/dotnet/1264283/CustId-3-Delete-01.jpg

我们为客户Pascagoula PetrochemicalsLtd提供详细信息,并可通过单击“ 删除 ”按钮将其删除

QuantumWeb应用程序客户页面:https//localhost:44306/Customers——2个客户

https://www.codeproject.com/KB/dotnet/1264283/Show-2-Cust-01.jpg

 

原文地址:https://www.codeproject.com/Articles/1264283/ASP-NET-Core-Razor-Pages-Using-EntityFramework-C-2

猜你喜欢

转载自blog.csdn.net/mzl87/article/details/85312335