ASP.NET Web API教程 创建Admin控制器实例分享(2)


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());Send a Request to the Controller


向控制器发送请求
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 :portnum/, where portnum is some port number.
此刻,我们还没有编写任何客户端代码,但你已经可以使用Web浏览器或诸如Fiddler之类的调试工具来调用这个Web API了。在Visual Studio中按F5键启动调试。你的浏览器将打开网址: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请求到“:portnum/api/admin”。第一次请求可能会慢一些才能完成,因为实体框架需要创建和种植数据库。其响应应当类似于下面这样:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdxfp.html