天天看點

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

目錄

介紹

使用代碼

完整的客戶CRUD

客戶創造

顯示客戶詳情

編輯客戶資訊

删除客戶記錄

完整的初始化CRUD頁面

  • 下載下傳源代碼(QuantumWeb)

介紹

這是一篇由多部分組成的文章的第二部分,示範了通過EntityFramework Core 2.1(EF)将C#enum值映射到資料庫表中的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

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

在“ Customer Create”頁面上并單擊“Create”輸入第一個Customer資料。

QuantumWeb應用程式客戶頁面:https//localhost: 44306/Customers/Create

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

QuantumWeb應用程式客戶頁面:https//localhost: 44306/Customers擁有第一位客戶

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

再添加兩個後Customers,我們顯示Customer頁面。

QuantumWeb應用程式客戶頁面:https//localhost: 44306/Customers——3個客戶

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

我們可以通過點選“詳細資訊”連結顯示customer的詳細資訊,聚烯烴加工公司。接下來列出Customers\Details.cshtml和Customers\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

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

QuantumWeb應用程式客戶頁面:https//localhost:44306/Customers——3個客戶

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

我們可以通過點選“ 編輯 ”連結來為customer編輯 Pascagoula Petrochemicals 的記錄。接下來列出Customers\Edit.cshtml和Customers\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

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

我們更改所選的Customer值并儲存更改。

QuantumWeb應用程式客戶頁面:https//localhost:44306/Customers——已更改客戶

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

我們看到了編輯過的值。現在,我們通過單擊“ 删除 ”連結删除Customer 。接下來列出Customers\Delete.cshtml和Customers\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

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

我們為客戶Pascagoula Petrochemicals,Ltd提供詳細資訊,并可通過單擊“ 删除 ”按鈕将其删除。

QuantumWeb應用程式客戶頁面:https//localhost:44306/Customers——2個客戶

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

下面可以進入第三部分進行學習。 

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

繼續閱讀