參考頁面:html
http://www.yuanjiaocheng.net/webapi/create-crud-api-1.htmlweb
http://www.yuanjiaocheng.net/webapi/create-crud-api-1-get.html數據庫
http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.htmljson
http://www.yuanjiaocheng.net/webapi/create-crud-api-1-put.htmlapi
http://www.yuanjiaocheng.net/webapi/create-crud-api-1-delete.html瀏覽器
注:本文是【ASP.NET Web API系列教程】的一部分,若是您是第一次看本博客文章,請先看前面的內容。app
本文引自:http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-3框架
In this section, we’ll add a Web API controller that supports CRUD (create, read, update, and delete) operations on products. The controller will use Entity Framework to communicate with the database layer. Only administrators will be able to use this controller. Customers will access the products through another controller.
在本小節中,咱們要添加一個對產品支持CRUD(建立、讀取、更新和刪除)操做的Web API控制器。該控制器將使用實體框架與數據庫層進行通訊。只有管理員纔可以使用這個控制器。客戶端將經過另外一個控制器訪問產品。asp.net
In Solution Explorer, right-click the Controllers folder. Select Add and then Controller.
在「解決方案資源管理器」中右擊Controllers文件夾,選擇「添加」,而後選「控制器」(見圖2-16)。ide
圖2-16. 添加控制器
In the Add Controller dialog, name the controller AdminController. Under Template, select "API controller with read/write actions, using Entity Framework". Under Model class, select "Product (ProductStore.Models)". Under Data Context, select "<New Data Context>".
在「添加控制器」對話框中,將此控制器命名爲AdminController。在「模板」下選擇「帶有讀/寫動做的API控制器(用實體框架)」。在「模型類」下選擇「Product (ProductStore.Models)」。在「數據上下文」下選擇「<新數據上下文>」(見圖2-17)。
圖2-17. 添加控制器對話框中的設置
If the Model class drop-down does not show any model classes, make sure you compiled the project. Entity Framework uses reflection, so it needs the compiled assembly.
若是「模型類」下拉列表未顯示任何模型類,請確保已編譯了此項目。實體框架使用反射,所以它須要已編譯的程序集。
Selecting "<New Data Context>" will open the New Data Context dialog. Name the data context ProductStore.Models.OrdersContext.
選擇「<新數據上下文>」會打開「新數據上下文」對話框。將該數據上下文命名爲ProductStore.Models.OrdersContext(見圖2-18)。
圖2-18. 命名「新數據上下文」
Click OK to dismiss the New Data Context dialog. In the Add Controller dialog, click Add.
點擊「OK」退出這個「新數據上下文」對話框。在「添加控制器」對話框中點擊「添加」。
Here's what got added to the project:
如下是添加到項目的內容:
上述新添加項見圖2-19。
圖2-19. 新添加到項目的內容
Open the OrdersContext.cs file. Notice that the constructor specifies the name of the database connection string. This name refers to the connection string that was added to Web.config.
打開OrdersContext.cs文件。注意,其構造器指明瞭數據庫鏈接字符串的名稱。該名稱是指被添加到Web.config的鏈接字符串。
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:
AdminController類定義了實現基本的CRUD功能的五個方法。每一個方法對應於一個客戶端能夠請求的URI(見表2-2):
Controller Method 控制器方法 |
Description 描述 |
URI | HTTP Method HTTP方法 |
---|---|---|---|
GetProducts | Gets all products. 獲取所有產品 |
api/products | GET |
GetProduct | Finds a product by ID. 根據ID查找一個產品 |
api/products/id | GET |
PutProduct | Updates a product. 更新一個產品 |
api/products/id | PUT |
PostProduct | Creates a new product. 建立一個新產品 |
api/products | POST |
DeleteProduct | Deletes a product. 刪除一個產品 |
api/products/id | DELETE |
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.
每個方法調用都會進入OrdersContext對數據庫進行查詢。對數據集進行修改的方法(PUT、POST以及DELETE)會調用db.SaveChanges,以便把這些修改持久化回數據庫。每一個HTTP請求都會建立控制器(實例),而後清除它。所以,在一個方法返回以前,對修改持久化是必要的。
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.
實體框架有一個很好的特性,它讓你在(應用程序)啓動時填充數據庫,並在模型發生修改時重建數據庫。這個特性在開發期間是有用的,由於你總會有一些測試數據,甚至會修改模型。
In Solution Explorer, right-click the Models folder and create a new class named OrdersContextInitializer. Paste in the following implementation:
在「解決方案資源管理器」中,右擊Models文件夾,並建立一個名稱爲OrdersContextInitializer的新類。粘貼如下實現:
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類的繼承,咱們是在告訴實體框架,不管什麼時候修改了模型類,便刪除數據庫。當實體框架建立(或重建)數據庫時,它會調用Seed方法去填充數據庫。咱們用這個Seed方法添加了一些例子產品和一個例子訂單。
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.
這個特性對於測試是很棒的,但在產品(指正式運行的應用程序 — 譯者注)中不要使用這個DropCreateDatabaseIfModelChanges類。由於,若是有人修改了模型類,便會丟失數據。
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());
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.
此刻,咱們尚未編寫任何客戶端代碼,但你已經能夠使用Web瀏覽器或諸如Fiddler之類的調試工具來調用這個Web API了。在Visual Studio中按F5鍵啓動調試。你的瀏覽器將打開網址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:
發送一個HTTP請求到「http://localhost:portnum/api/admin」。第一次請求可能會慢一些才能完成,由於實體框架須要建立和種植數據庫。其響應應當相似於下面這樣:
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}]
看完此文若是以爲有所收穫,懇請給個推薦