在本部分中,你將添加用于定義數(shù)據(jù)庫實(shí)體的模型類。然后你將添加用于在這些實(shí)體上執(zhí)行CRUD(Create、Retrieve、Update、Delete——譯者注)操作的Web API 控制器。
在本教程中,我們將通過使用“Code First”的方法對(duì)實(shí)體框架(EF)來創(chuàng)建數(shù)據(jù)庫。對(duì)于Code First,你寫C#類來相應(yīng)數(shù)據(jù)庫表,使用EF來創(chuàng)建數(shù)據(jù)庫。(有關(guān)詳細(xì)信息,見Entity Framework Development Approaches.)
首先,我們定義我們的域?qū)ο笞鳛镻OCO。我們將創(chuàng)建以下POCO: Author Book
在解決方案資源管理中,右擊Models文件夾。選擇Add,然后選擇Class。名為這個(gè)類為Author。
用以下代碼替換Author.cs中的所有樣板代碼。
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace BookService.Models
{
public class Author
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
添加另一個(gè)命名為Book的類,并替換成以下代碼。
using System.ComponentModel.DataAnnotations;
namespace BookService.Models
{
public class Book
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public string Genre { get; set; }
// Foreign Key
public int AuthorId { get; set; }
// Navigation property
public Author Author { get; set; }
}
}
Entity Framework將使用這些模型來創(chuàng)建數(shù)據(jù)庫表。對(duì)于每一個(gè)模型,Id屬性將變成數(shù)據(jù)庫表的主鍵列。
在Book類中,AuthorId定義了一個(gè)外鍵到Author表。(簡單起見,我假定每本書只有一個(gè)作者。)該book類還包含一個(gè)導(dǎo)航屬性給相關(guān)的Author。 你可以使用導(dǎo)航屬性在代碼中訪問相關(guān)的作者。我在【W(wǎng)eb API系列教程】3.4 — 實(shí)戰(zhàn):處理數(shù)據(jù)(處理實(shí)體關(guān)系) 中描述了關(guān)于導(dǎo)航屬性的更多信息。
在這部分,我們將添加支持CRUD(create, read, update 和 delete)的Web API 控制器。這些控制器使用Entity Framework來同數(shù)據(jù)庫層交流。
首先,你應(yīng)該刪除Controllers目錄下的ValuesControllers.cs文件。這個(gè)文件包含了一個(gè)Web API示例,但對(duì)于本教程你并不需要它。
然后,編譯這個(gè)項(xiàng)目。Web API框架使用反射來發(fā)現(xiàn)這個(gè)模型類,所以它需要編譯程序集。
在Solution Explorer中,右擊Controllers文件夾。選擇Add,然后選擇Controller。
在Add Scaffold對(duì)話框中,選擇“Web API 2 controller with actions, using Entity Framework”。點(diǎn)擊Add。
在Add Controller對(duì)話框中,執(zhí)行以下操作: 1, 在模型類下拉框中,選擇Author類。(如果你沒有在下拉框中看到它,請(qǐng)確保已經(jīng)編譯了這個(gè)項(xiàng)目。) 2, 選中“Use async controller action”。 3, 保留控制器名稱為“AuthorsController”。 4, 點(diǎn)擊加號(hào)(+)按鈕下一步到Data Context Class.
在New Data Context對(duì)話框中,保留默認(rèn)名稱并點(diǎn)擊Add。
點(diǎn)擊Add以完成Add Controller對(duì)話框。這個(gè)對(duì)話將添加兩個(gè)類到你的項(xiàng)目中: AuthorsController定義了一個(gè)Web API控制器。這個(gè)控制器實(shí)現(xiàn)了REST API,客戶端使用它來在authors列表上執(zhí)行CRUD操作。 BookServiceContext在運(yùn)行時(shí)管理實(shí)體對(duì)象,包括從數(shù)據(jù)庫中聚集對(duì)象數(shù)據(jù)、追蹤、保留數(shù)據(jù)到數(shù)據(jù)庫。它繼承自DBContext。
在這個(gè)節(jié)點(diǎn)上,再次編譯這個(gè)項(xiàng)目?,F(xiàn)在再過一遍相同的步驟為Book實(shí)體添加API控制器。這次選擇Book作為模型類,并選擇已經(jīng)存在的BookServiceContext類作為數(shù)據(jù)上下文類。(不要再創(chuàng)建新的數(shù)據(jù)上下文。)點(diǎn)擊Add以添加該控制器。