In this section, we'll add a WEB API controller that supports CRUD (create, read, update, and delete) operations on Produc Ts. The controller would use the Entity Framework to communicate with the database layer. Only administrators is able to use this controller. Customers'll access the products through another controller.
In this section, we add a Web API controller that supports CRUD (create, read, update, and delete) operations for the product. The controller communicates with the database layer using the Entity Framework. Only administrators can use this controller. The client will access the product through another controller.
In Solution Explorer, right-click the Controllers folder. Select Add and then Controller.
Right-click the Controllers folder in Solution Explorer, select Add, and then choose controller (see Figure 2-16).
Figure 2-16. Add 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 Templates, select the API controller with read/write actions (with Entity Framework). Under Model classes, select Product (productstore.models). Under Data context, select < New data context > (see Figure 2-17).
Figure 2-17. Add settings in the Controller dialog box
If the Model class Drop-down does not show any Model classes, make sure you compiled the project. The Entity Framework uses reflection, so it needs the compiled assembly.
If the model class Drop-down list does not show any model classes, make sure that you have compiled this project. The Entity Framework uses reflection, so it requires a compiled assembly.
Selecting "<new Data context>" would open the New Data context dialog. Name the data context ProductStore.Models.OrdersContext.
Selecting < New Data context > Opens the New Data Context dialog box. Name the data context as 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:
Here's what you add to your project:
A class named Orderscontext that derives from DbContext. This class provides the glue between the POCO models and the database.
A Orderscontext class called, which derives from DbContext. This class provides the glue between the POCO model and the database.
A Web API Controller named Admincontroller. This is controller supports CRUD operations on Product instances. It uses the Orderscontext class to communicate with Entity Framework.
A Web API controller called Admincontroller. This controller supports CRUD operations on the product instance. It communicates with the Entity Framework using the Orderscontext class.
A New Database connection string in the Web.config file.
A new database connection string in the Web.config file.
The above new additions are shown in Figure 2-19.
Figure 2-19. New 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 is added to Web.config.
Open the OrdersContext.cs file. Note that its constructor indicates the name of the database connection string. The name refers to the connection string that is added to the web.config.
Copy Code code as follows:
Public Orderscontext (): Base ("Name=orderscontext") Add the following properties to the Orderscontext class:
Add the following properties to the Orderscontext class:
Copy Code code as follows:
Public dbset<order> Orders {get; set;}
Public dbset<orderdetail> OrderDetails {get; set;}
A dbset represents a set of entities that can is queried. Here's the complete listing for the Orderscontext class:
Dbset represents a set of entities that can be queried. Here's a complete list of the Orderscontext classes:
Copy Code code 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 for implementing basic CRUD functionality. Each method corresponds to a URI that the client can request (see table 2-2):
Table 2-2. Five ways to implement CRUD operations in Admincontroller
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 are necessary to persist changes-a method before.
Every method call goes into Orderscontext to query the database. Methods that modify the dataset (put, post, and delete) Invoke db.savechanges to persist the modifications back to the database. Each HTTP request creates a controller (instance) and then clears it. Therefore, it is necessary to modify the persistence before a method returns.
Add a Database initializer
To add a database initializer
Entity Framework has a nice feature this lets you populate the database on startup, and automatically recreate the Databas E whenever the models change. This feature is useful during development, because you always have some test data, even if you are change the models.
The Entity Framework has a good feature that lets you populate the database at startup (application) and rebuild the database when the model changes. 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 called Orderscontextinitializer. Paste the following implementation:
Copy Code code 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.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
};
Context. Orders.add (order);
Od. ForEach (o => context. Orderdetails.add (o));
Context. SaveChanges ();
}
}
}
By inheriting from the Dropcreatedatabaseifmodelchanges class, we are are telling Entity Framework to drop the database Whenev Er 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 a example order.
By inheriting from 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 rebuilds) a database, it invokes the seed method to populate the database. We have added some example products and an example order with this seed method.
This feature is great to testing, but don ' t use the Dropcreatedatabaseifmodelchanges class in production, because you cou LD Lose your data if someone changes a model class.
This feature is great for testing, but do not use this dropcreatedatabaseifmodelchanges class in a product, which is a formally running application-translator note. Because if someone modifies the model class, the data is 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 Code code as follows:
System.Data.Entity.Database.SetInitializer (
New ProductStore.Models.OrdersContextInitializer ()); Send a Request to the Controller
To send a request to a controller
At I, we haven ' t written any client code, but can invoke the Web API using a Web browser or a HTTP debugging Tool such as Fiddler. In Visual Studio, press F5 to start debugging. Your Web browser'll open to http://localhost:portnum/, where Portnum is some port number.
At this point, we haven't written any client code yet, but you can already invoke the Web API using a Web browser or debugging tools such as Fiddler. Press the F5 key 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 I request may is slow to complete, because entify Entity Framework needs to create and seed the database. The response should 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 grow the database. The response should resemble the following:
Copy Code code as follows:
http/1.1 OK
Server:ASP.NET Development server/10.0.0.0
Date:mon, June 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, if you feel a harvest, please give a recommendation