This exercise is based this page:
Overview and creating the Project
This tutorial shows how to use WEBAPI and ADO.NET Entity framework using code-first model. UI using Knockout.
Goal: simple store application. Normal user can view products and create orders; admin users can create, delete or edit products.
How domain objects are represented in various layers
(1) create a new MVC4 internet application “ProductStore”.
(2) Update the /Content/site.css per the exercise.
Creating Domain Models
(3) Define 3 models:
(4) Build the solution so EF can discover the new models.
(5) Add to WebApiConfig.cs so we can resolve circular reference issue in JSON and also remove XMLFormatter (so JSON is the default formatter).
Creating an Admin Controller
(6) We add an API controller that supports CRUD operations on Product.
Add a new controller (AdminController)
(7) A OrdersContext.cs is created under /Models.
(8) Update the web.config so the data context points to a SQL server, not SQL CE or SQL Express.
(9) On Orders.Context.cs: this name refers to the connection string name:
(10) In OrdersContext.cs, add these three lines after the constructor so EF can query them:
AdminController defines these 5 methods:
(11) Add database initializer – to seed the DB.
Right click /Models, add a new class OrdersContextInitializer.cs.
Then in global.asax’s Application_Start, add this line to initialize the database every time the application starts.
(12) Now when you do Control + F5, and
http://localhost:55784/api/admin you get this JSON result:
because in AdminController, the default get method returns all products as an enumerable: