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.
In this section, we will add a Web API controller that supports CRUD (create, read, update, and delete) operations on the product. The controller uses the Entity Framework to communicate with the database layer. Only Administrators can use this controller. The client accesses the product through another controller.
In Solution Explorer, right-click the Controllers folder. Select Add and then Controller.
In Solution Explorer, right-click the Controllers folder, select add, and select Controller (see Figure 2-16 ).
Figure 2-16. Add a controller
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> ".
In the Add controller dialog box, name the Controller AdminController. Under "template", select "API controller with read/write actions (with Entity Framework )". Under "model class", select "Product (ProductStore. Models )". Under "data context", select "<new data context>" (see Figure 2-17 ).
Figure 2-17. settings in the Add controller dialog box
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.
If the drop-down list of "Model classes" does not display any model classes, make sure that the project has been compiled. The Entity Framework uses reflection, so it requires compiled assembly.
Selecting "<New Data Context>" will open the New Data Context dialog. Name the data context ProductStore. Models. OrdersContext.
Select <new data context> to open the "new data context" dialog box. Name the data context ProductStore. Models. OrdersContext (see Figure 2-18 ).
Figure 2-18. Name "new data context"
Click OK to dismiss the New Data Context dialog. In the Add Controller dialog, click Add.
Click "OK" to exit the "new data context" dialog box. In the "add controller" dialog box, click "add ".
Here's what got added to the project:
The following content is added to the project:
A class named OrdersContext that derives from DbContext. This class provides the glue between the POCO models and the database.
An OrdersContext class, which is derived from DbContext. This class provides the bond between the POCO model and the database.
A Web API controller named AdminController. This controller supports CRUD operations on Product instances. It uses the OrdersContext class to communicate with Entity Framework.
A Web API controller named AdminController. This controller supports CRUD operations on the Product instance. It uses the OrdersContext class to communicate with the object framework.
A new database connection string in the Web. config file.
A new database connection string in the Web. config file.
See figure 2-19.
Figure 2-19. content added to the project
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.
Open the OrdersContext. cs file. Note that the constructor specifies the name of the database connection string. The name is the connection string added to Web. config.
Copy codeThe Code is as follows: public OrdersContext (): base ("name = OrdersContext") Add the following properties to the OrdersContext class:
Add the following attributes to the OrdersContext class:Copy codeThe Code is as follows: 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 indicates a group of entities that can be queried. The following is a complete list of OrdersContext classes:Copy codeThe Code is as follows: 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:
Class defines five methods to implement basic CRUD functions. Each method corresponds to the URI that a client can request (see Table 2-2 ):
Table 2-2. Five CRUD operations in AdminController
Table
Each method callinto 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.
Each method call will go to OrdersContext to query the database. Db. SaveChanges is called to modify the dataset (PUT, POST, and DELETE) so that these modifications can be persisted back to the database. Each HTTP request creates a controller (instance) and clears it. Therefore, modification persistence is necessary before a method is returned.
Add a Database Initializer
Add database initializer
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.
The Entity Framework has a good feature that enables you to fill in the database at (Application) Startup and recreate the database when the model is modified. This feature is useful during development because you will always have some test data and even modify the model.
In Solution Explorer, right-click the Models folder and create a new class named OrdersContextInitializer. Paste in the following implementation:
In Solution Explorer, right-click the Models folder and create a new class named OrdersContextInitializer. Paste the following implementation:Copy codeThe Code is as follows: 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.39 M, ActualCost =. 99 M },
New Product () {Name = "Hammer", Price = 16.99 M, ActualCost = 10 },
New Product () {Name = "Yo yo", Price = 6.99 M, ActualCost = 2.05 M}
};
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 callthe Seed method to populate the tables. we use the Seed method to add some example products plus an example order.
By inheriting the DropCreateDatabaseIfModelChanges class, we are telling the Entity Framework to delete the database whenever the model class is modified. When the Entity Framework creates (or recreates) a database, it calls the Seed method to fill the database. We use this Seed method to add some example products and an example Order.
This feature is great for testing, but don't use the DropCreateDatabaseIfModelChanges class in production, because you cocould lose your data if someone changes a model class.
This feature is great for testing, but do not use this DropCreateDatabaseIfModelChanges class in the product (the application that officially runs-the Translator's note. Because if someone modifies the model class, data will be lost.
Next, open Global. asax and add the following code to the Application_Start method:
Next, open Global. asax and add the following code to the Application_Start method:Copy codeThe Code is as follows: System. Data. Entity. Database. SetInitializer (
New ProductStore. Models. OrdersContextInitializer (); Send a Request to the Controller
Send request to 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 http: // localhost: portnum/, where portnum is some port number.
At this moment, we have not compiled any client code, but you can use a Web browser or debugging tool such as Fiddler to call this Web API. Press F5 in Visual Studio to start debugging. Your browser will open the URL http: // localhost: portnum/. Here, portnum is a port number.
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 shoshould something similar to the following:
Send an HTTP request to "http: // localhost: portnum/api/admin ". The first request may be slow to complete, because the Entity Framework needs to create and implant databases. The response should be similar to the following:Copy codeThe Code is as follows: 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}]
After reading this article, I 'd like to recommend you