我們打算使用code-first方法,因此,首先把域?qū)ο蠖x成POCO(plain-old CLR objects — 舊式無(wú)格式公共語(yǔ)言運(yùn)行時(shí)(CLR)對(duì)象。很多人不太理解POCO對(duì)象,其實(shí)這種對(duì)象就像文本文件一樣,是一種最簡(jiǎn)單、最原始、不帶任何格式的對(duì)象。因此,在各種環(huán)境中最容易對(duì)這類對(duì)象進(jìn)行處理,包括用各類語(yǔ)言進(jìn)行處理 — 譯者注)。利用code-first方法,域?qū)ο蟛恍枰魏胃郊哟a去支持?jǐn)?shù)據(jù)庫(kù)層,如事務(wù)處理、持久化等。(特別是它們不需要繼承于EntityObject類。)你仍可以使用數(shù)據(jù)注解(data annotation)對(duì)實(shí)體框架如何創(chuàng)建數(shù)據(jù)庫(kù)方案進(jìn)行控制。
Because POCOs do not carry any extra properties that describe database state, they can easily be serialized to JSON or XML. However, that does not mean you should always expose your Entity Framework models directly to clients, as we'll see later in the tutorial.
由于POCO不帶描述數(shù)據(jù)庫(kù)狀態(tài)的任何附加屬性,它們可以很容易地被序列化成JSON或XML。然而,這并不意味著你應(yīng)當(dāng)總是把實(shí)體框架模型直接暴露給客戶端,就像我們稍后在本教程所看到的那樣。
We will create the following POCOs:
我們將創(chuàng)建以下POCO:
Product
Order
OrderDetail
To create each class, right-click the Models folder in Solution Explorer. From the context menu, select Add and then select Class.
要?jiǎng)?chuàng)建每個(gè)類,在“解決方案資源管理器”中右擊Models文件夾。從上下文菜單選擇“添加”,然后選擇“類”(如圖2-14所示)。
圖2-14. 創(chuàng)建POCO類
Add a Product class with the following implementation:
用以下實(shí)現(xiàn)添加一個(gè)Product類(產(chǎn)品類):
代碼如下:
namespace ProductStore.Models
{
using System.ComponentModel.DataAnnotations;
public class Product
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public decimal ActualCost { get; set; }
}
}
By convention, Entity Framework uses the Id property as the primary key and maps it to an identity column in the database table. When you create a new Product instance, you won't set a value for Id, because the database generates the value.
根據(jù)約定,實(shí)體框架用Id屬性作為主鍵,并把它映射成數(shù)據(jù)庫(kù)表中的標(biāo)識(shí)列。當(dāng)創(chuàng)建一個(gè)新的Product實(shí)例時(shí),不必為Id設(shè)置值,因?yàn)閿?shù)據(jù)庫(kù)會(huì)生成它。
The ScaffoldColumn attribute tells ASP.NET MVC to skip the Id property when generating an editor form. The Required attribute is used to validate the model. It specifies that the Name property must be a non-empty string.
ScaffoldColumn(支架列)注解屬性是告訴ASP.NET MVC,在生成編輯表單時(shí),跳過(guò)這個(gè)Id屬性。Required注解屬性用于對(duì)模型進(jìn)行驗(yàn)證。它指定Name屬性必須是一個(gè)非空字符串。
注:本文把ScaffoldConlumn、Required等這一類英文中叫做Annotation Attribute的屬性(Attribute)譯為注解屬性(Annotation Attribute),以便與類中的那些屬性加以區(qū)別 — 譯者注
Add the Order class:
添加Order類(訂單類):
代碼如下:
namespace ProductStore.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Order
{
public int Id { get; set; }
[Required]
public string Customer { get; set; }
// Navigation property
// 導(dǎo)航屬性
public ICollection<OrderDetail> OrderDetails { get; set; }
}
}
Add the OrderDetail class:
添加OrderDetail類(訂單細(xì)節(jié)類,或訂單詳情類):
代碼如下:
namespace ProductStore.Models
{
public class OrderDetail
{
public int Id { get; set; }
public int Quantity { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
// Navigation properties
public Product Product { get; set; }
public Order Order { get; set; }
}
}
Foreign Key Relations
外鍵關(guān)系
An order contains many order details, and each order detail refers to a single product. To represent these relations, the OrderDetail class defines properties named OrderId and ProductId. Entity Framework will infer that these properties represent foreign keys, and will add foreign-key constraints to the database.
一份訂單包含很多訂單細(xì)節(jié),而每個(gè)訂單細(xì)節(jié)指向一個(gè)單一的產(chǎn)品。為了表示這些關(guān)系,OrderDetail類定義了名稱為OrderId和ProductId的屬性。實(shí)體框架將會(huì)推斷出這些屬性表示的是外鍵,并會(huì)把外鍵約束添加到數(shù)據(jù)庫(kù)(見圖2-15)。
圖2-15. 外鍵關(guān)系
The Order and OrderDetail classes also include “navigation” properties, which contain references to the related objects. Given an order, you can navigate to the products in the order by following the navigation properties.
Order和OrderDetail類也包含了“導(dǎo)航(navigation)”屬性,導(dǎo)航屬性包含了對(duì)相關(guān)對(duì)象的引用。對(duì)于一份給定的訂單,可以根據(jù)導(dǎo)航屬性導(dǎo)航到這份訂單的產(chǎn)品。
Compile the project now. Entity Framework uses reflection to discover the properties of the models, so it requires a compiled assembly to create the database schema.
現(xiàn)在,編譯這個(gè)項(xiàng)目。實(shí)體框架會(huì)使用反射來(lái)發(fā)現(xiàn)這些模型的屬性,因此它需要編譯后的程序集來(lái)創(chuàng)建相應(yīng)的數(shù)據(jù)庫(kù)方案(這里的數(shù)據(jù)庫(kù)方案意指數(shù)據(jù)庫(kù)、表結(jié)構(gòu)以及關(guān)系等數(shù)據(jù)庫(kù)方面的定義 — 譯者注)。
Configure the Media-Type Formatters
配置Media-Type格式化器
A media-type formatter is an object that serializes your data when Web API writes the HTTP response body. The built-in formatters support JSON and XML output. By default, both of these formatters serialize all objects by value.
media-type(媒體類型)格式化器是Web API書寫HTTP響應(yīng)體時(shí)對(duì)數(shù)據(jù)進(jìn)行序列化的一個(gè)對(duì)象。內(nèi)建的格式化器支持JSON和XML
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// New code:
// 新代碼:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
This code sets the JSON formatter to preserve object references, and removes the XML formatter from the pipeline entirely. (You can configure the XML formatter to preserve object references, but it's a little more work, and we only need JSON for this application. For more information, see Handling Circular Object References.)
這段代碼把JSON格式化器設(shè)置為防止對(duì)象引用(“新代碼”第二行的作用 — 譯者注),并把XML格式化器從管線(指HTTP的請(qǐng)求處理管線 — 譯者注)中完全刪除(“新代碼”最后一行的作用 — 譯者注)。(你也可以把XML格式化器配置成防止對(duì)象引用,但這還要做一點(diǎn)工作,而對(duì)于這個(gè)應(yīng)用程序,我們只需要JSON。更多信息參閱“處理循環(huán)對(duì)象引用”聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com