1. 程式人生 > >使用EntityFramework Core和Enums作為字串的ASP.NET Core Razor頁面——第二部分

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

目錄

介紹

使用程式碼

完整的客戶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