"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Part 3: Creating an Admin Controller

by Mike Wasson

Download Completed Project

Add an Admin Controller

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 Solution Explorer, right-click the Controllers folder. Select Add and then 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>”.

[!NOTE] 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.

Click OK to dismiss the New Data Context dialog. In the Add Controller dialog, click Add.

Here’s what got 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.

[!code-csharpMain]

   1:  public OrdersContext() : base("name=OrdersContext")

Add the following properties to the OrdersContext class:

[!code-csharpMain]

   1:  public DbSet<Order> Orders { get; set; }
   2:  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:

[!code-csharpMain]

   1:  public class OrdersContext : DbContext
   2:  {
   3:      public OrdersContext() : base("name=OrdersContext")
   4:      {
   5:      }
   6:   
   7:      public DbSet<Order> Orders { get; set; }
   8:      public DbSet<OrderDetail> OrderDetails { get; set; }
   9:      public DbSet<Product> Products { get; set; }
  10:  }

The AdminController class defines five methods that implement basic CRUD functionality. Each method corresponds to a URI that the client can invoke:

Controller Method Description URI HTTP Method
GetProducts Gets all products. api/products GET
GetProduct Finds a product by 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.

Add a 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.

In Solution Explorer, right-click the Models folder and create a new class named OrdersContextInitializer. Paste in the following implementation:

[!code-csharpMain]

   1:  namespace ProductStore.Models
   2:  {
   3:      using System;
   4:      using System.Collections.Generic;
   5:      using System.Data.Entity;
   6:   
   7:      public class OrdersContextInitializer : DropCreateDatabaseIfModelChanges<OrdersContext>
   8:      {
   9:          protected override void Seed(OrdersContext context)
  10:          {
  11:              var products = new List<Product>()            
  12:              {
  13:                  new Product() { Name = "Tomato Soup", Price = 1.39M, ActualCost = .99M },
  14:                  new Product() { Name = "Hammer", Price = 16.99M, ActualCost = 10 },
  15:                  new Product() { Name = "Yo yo", Price = 6.99M, ActualCost = 2.05M }
  16:              };
  17:   
  18:              products.ForEach(p => context.Products.Add(p));
  19:              context.SaveChanges();
  20:   
  21:              var order = new Order() { Customer = "Bob" };
  22:              var od = new List<OrderDetail>()
  23:              {
  24:                  new OrderDetail() { Product = products[0], Quantity = 2, Order = order},
  25:                  new OrderDetail() { Product = products[1], Quantity = 4, Order = order }
  26:              };
  27:              context.Orders.Add(order);
  28:              od.ForEach(o => context.OrderDetails.Add(o));
  29:   
  30:              context.SaveChanges();
  31:          }
  32:      }
  33:  }

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.

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.

Next, open Global.asax and add the following code to the Application_Start method:

[!code-csharpMain]

   1:  System.Data.Entity.Database.SetInitializer(
   2:      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 http://localhost:*portnum*/, where portnum is some port number.

Send an HTTP request to “http://localhost:*portnum*/api/admin. The first request may be slow to complete, because Entify Framework needs to create and seed the database. The response should something similar to the following:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Server: ASP.NET Development Server/10.0.0.0
   3:  Date: Mon, 18 Jun 2012 04:30:33 GMT
   4:  X-AspNet-Version: 4.0.30319
   5:  Cache-Control: no-cache
   6:  Pragma: no-cache
   7:  Expires: -1
   8:  Content-Type: application/json; charset=utf-8
   9:  Content-Length: 175
  10:  Connection: Close
  11:   
  12:  [{"Id":1,"Name":"Tomato Soup","Price":1.39,"ActualCost":0.99},{"Id":2,"Name":"Hammer",
  13:  "Price":16.99,"ActualCost":10.00},{"Id":3,"Name":"Yo yo","Price":6.99,"ActualCost":
  14:  2.05}]

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/older-versions/using-web-api-1-with-entity-framework-5/using-web-api-with-entity-framework-part-3.htm
< THANKS ME>