public OrdersContext() : base("name=OrdersContext")Add the following properties to the OrdersContext class:
將以下屬性添加到OrdersContext類:
代碼如下:
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
A DbSet represents a set of entities that can be queried. Here is the complete listing for the OrdersContext class:
DbSet表示一組能夠被查詢的實體。以下是這個OrdersContext類的完整清單:
代碼如下:
public class OrdersContext : DbContext
{
public OrdersContext() : base("name=OrdersContext")
{
}
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Product> Products { get; set; }
}
The AdminController class defines five methods that implement basic CRUD functionality. Each method corresponds to a URI that the client can invoke:
類定義了實現(xiàn)基本的CRUD功能的五個方法。每個方法對應(yīng)于一個客戶端可以請求的URI(見表2-2):
表2-2. AdminController中實現(xiàn)CRUD操作的五個方法
table
Each method calls into OrdersContext to query the database. The methods that modify the collection (PUT, POST, and DELETE) call db.SaveChanges to persist the changes to the database. Controllers are created per HTTP request and then disposed, so it is necessary to persist changes before a method returns.
每一個方法調(diào)用都會進(jìn)入OrdersContext對數(shù)據(jù)庫進(jìn)行查詢。對數(shù)據(jù)集進(jìn)行修改的方法(PUT、POST以及DELETE)會調(diào)用db.SaveChanges,以便把這些修改持久化回數(shù)據(jù)庫。每個HTTP請求都會創(chuàng)建控制器(實例),然后清除它。因此,在一個方法返回之前,對修改持久化是必要的。
Add a Database Initializer
添加數(shù)據(jù)庫初始化器
Entity Framework has a nice feature that lets you populate the database on startup, and automatically recreate the database whenever the models change. This feature is useful during development, because you always have some test data, even if you change the models.
實體框架有一個很好的特性,它讓你在(應(yīng)用程序)啟動時填充數(shù)據(jù)庫,并在模型發(fā)生修改時重建數(shù)據(jù)庫。這個特性在開發(fā)期間是有用的,因為你總會有一些測試數(shù)據(jù),甚至?xí)薷哪P汀?
In Solution Explorer, right-click the Models folder and create a new class named OrdersContextInitializer. Paste in the following implementation:
在“解決方案資源管理器”中,右擊Models文件夾,并創(chuàng)建一個名稱為OrdersContextInitializer的新類。粘貼以下實現(xiàn):
代碼如下:
namespace ProductStore.Models
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
public class OrdersContextInitializer : DropCreateDatabaseIfModelChanges<OrdersContext>
{
protected override void Seed(OrdersContext context)
{
var products = new List<Product>()
{
new Product() { Name = "Tomato Soup", Price = 1.39M, ActualCost = .99M },
new Product() { Name = "Hammer", Price = 16.99M, ActualCost = 10 },
new Product() { Name = "Yo yo", Price = 6.99M, ActualCost = 2.05M }
};
products.ForEach(p => context.Products.Add(p));
context.SaveChanges();
var order = new Order() { Customer = "Bob" };
var od = new List<OrderDetail>()
{
new OrderDetail() { Product = products[0], Quantity = 2, Order = order},
new OrderDetail() { Product = products[1], Quantity = 4, Order = order }
};
context.Orders.Add(order);
od.ForEach(o => context.OrderDetails.Add(o));
context.SaveChanges();
}
}
}
By inheriting from the DropCreateDatabaseIfModelChanges class, we are telling Entity Framework to drop the database whenever we modify the model classes. When Entity Framework creates (or recreates) the database, it calls the Seed method to populate the tables. We use the Seed method to add some example products plus an example order.
通過對DropCreateDatabaseIfModelChanges類的繼承,我們是在告訴實體框架,無論何時修改了模型類,便刪除數(shù)據(jù)庫。當(dāng)實體框架創(chuàng)建(或重建)數(shù)據(jù)庫時,它會調(diào)用Seed方法去填充數(shù)據(jù)庫。我們用這個Seed方法添加了一些例子產(chǎn)品和一個例子訂單。
This feature is great for testing, but don't use the DropCreateDatabaseIfModelChanges class in production, because you could lose your data if someone changes a model class.
這個特性對于測試是很棒的,但在產(chǎn)品(指正式運行的應(yīng)用程序 — 譯者注)中不要使用這個DropCreateDatabaseIfModelChanges類。因為,如果有人修改了模型類,便會丟失數(shù)據(jù)。
Next, open Global.asax and add the following code to the Application_Start method:
下一步,打開Global.asax,并將以下代碼添加到Application_Start方法中:
代碼如下:
System.Data.Entity.Database.SetInitializer(
new ProductStore.Models.OrdersContextInitializer());Send a Request to the Controller
向控制器發(fā)送請求
At this point, we haven't written any client code, but you can invoke the web API using a web browser or an HTTP debugging tool such as Fiddler. In Visual Studio, press F5 to start debugging. Your web browser will open to http://localhost:portnum/, where portnum is some port number.
此刻,我們還沒有編寫任何客戶端代碼,但你已經(jīng)可以使用Web瀏覽器或諸如Fiddler之類的調(diào)試工具來調(diào)用這個Web API了。在Visual Studio中按F5鍵啟動調(diào)試。你的瀏覽器將打開網(wǎng)址http://localhost:portnum/,這里,portnum是某個端口號。
Send an HTTP request to "http://localhost:portnum/api/admin". The first request may be slow to complete, because Entify Entity Framework needs to create and seed the database. The response should something similar to the following:
發(fā)送一個HTTP請求到“http://localhost:portnum/api/admin”。第一次請求可能會慢一些才能完成,因為實體框架需要創(chuàng)建和種植數(shù)據(jù)庫。其響應(yīng)應(yīng)當(dāng)類似于下面這樣:
代碼如下:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 18 Jun 2012 04:30:33 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 175
Connection: Close
[{"Id":1,"Name":"Tomato Soup","Price":1.39,"ActualCost":0.99},{"Id":2,"Name":"Hammer",
"Price":16.99,"ActualCost":10.00},{"Id":3,"Name":"Yo yo","Price":6.99,"ActualCost":
2.05}]
看完此文如果覺得有所收獲,懇請給個推薦聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com