Part 3:-Learn using Web API with Entity Framework(Creating an Admin Controller)

Rama Sagar
Posted by in ASP.NET Web API category on for Beginner level | Points: 250 | Views : 20450 red flag

In Web API, a controller is an object that handles HTTP requests.

Introduction


In this article we will see how to add a Web API controller..In this context we’ll add a Web API controller that supports CRUD (create, read, update, and delete) operations on Books.

Objective


The Objective of this article is to show how 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 Books through another controller.


Before we proceed please have a look at Part 2 article 


  • Step1 In Solution Explorer, right-click the Controllers folder. Select Add and then Controller.
    


Enter the details as shown 

    


If the Model class drop-down does not show any model classes as shown above, make sure you compiled the project and add it again.







Here we can see the new solution structure



Modify the context class as shown below
using System.Data.Entity;

namespace BooksStore.Models
{
    public class OrdersContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<BooksStore.Models.OrdersContext>());
        
        
        //This name refers to the connection string that was added to Web.config.
        public OrdersContext() : base("name=OrdersContext")
        {
        }

        //A DbSet represents a set of entities that can be queried. Here is the complete listing
        public DbSet<Book> Books { get; set; }

        //New code
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
    }
}


  • Step2 : Now lets add Database Intializer
  In Solution Explorer, right-click the Models folder and create a new class named OrdersContextInitializer and add the following Implementation
  
using System.Collections.Generic;
using System.Data.Entity;

namespace BooksStore.Models
{
    //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.
   
    public class OrdersContextInitializer : DropCreateDatabaseIfModelChanges<OrdersContext>
    {
        protected override void Seed(OrdersContext context)
        {
            var books = new List<Book>()            
            {
                new Book() { Name = "Practical ASP.NET Web API", DealPrice = 1.39M, SellingPrice = .88M },
                new Book() { Name = "Pro ASP.NET 4.5 in VB, 5th Edition", DealPrice = 16.99M, SellingPrice = 40 },
                new Book() { Name = "Beginning ASP.NET MVC 4", DealPrice = 6.99M, SellingPrice = 4.05M }
            };

            books.ForEach(p => context.Books.Add(p));
            context.SaveChanges();

            var order = new Order() { Customer = "Sagar" };
            var od = new List<OrderDetail>()
            {
                new OrderDetail() { Book = books[0], Quantity = 2, Order = order},
                new OrderDetail() { Book = books[1], Quantity = 4, Order = order }
            };
            context.Orders.Add(order);
            od.ForEach(o => context.OrderDetails.Add(o));

            context.SaveChanges();
        }
    }
}





                     Part 4 :-Learn using Web API with Entity Framework(Adding an Admin View)                                                           



Conclusion

In this article we have learned how to create web API controller in our project

Reference

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)