Introduction
In Part 1 of this "Using Entity Framework in Web API " series of articles we explained how to create a application and add the Model class. Now in this article we will explain how to add the Web API Controller with the Entity Framework.
Step 1
Use the following procedure to create the Controller:
- In the Solution Explorer.
- Right-click on the Controller Folder.
- Select "Add" -> "Controller".
- Select Template "API Controller with read/write actions, using Entity Framework".
- Select "Model class" from the drop down list:
- Now select "DataContext" by clicking on the new data context.
- Now see the Solution Explorer.
Step 2
Now perform some changes in the Context file "ItemsContext".
- using System.Data.Entity;
- namespace EntityAPI.Models
- {
- public class ItemsContext : DbContext
- {
-
-
-
-
-
-
-
-
- public ItemsContext() : base("name=ItemsContext")
- {
- }
- public DbSet<Novel> Novels { get; set; }
- public DbSet<Item> Items { get; set; }
- public DbSet<ItemDetail> ItemDetails { get; set; }
- }
- }
Step 3
Now add a database initializer to the Model class.
- In the "Solution Explorer".
- Right-click on the "Model Folder".
- Select "Class".
- Click on the "OK" button.
Add the following code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.Entity;
- namespace EntityAPI.Models
- {
- public class ItemsContextInitializer : DropCreateDatabaseIfModelChanges<ItemsContext>
- {
- protected override void Seed(ItemsContext context)
- {
- var novels = new List<Novel>()
- {
- new Novel() { Name = "Revolution 2020", DealPrice = 140, SellingPrice = 145 },
- new Novel() { Name = "A Calender too Crowded", DealPrice = 295, SellingPrice = 300 },
- new Novel() { Name = "How That yor are rich", DealPrice = 100, SellingPrice = 110 }
- };
- novels.ForEach(p => context.Novels.Add(p));
- context.SaveChanges();
- var item = new Item() { Customer = "Smith" };
- var od = new List<ItemDetail>()
- {
- new ItemDetail() { Novel = novels[0], Quantity = 2, Item = item},
- new ItemDetail() { Novel = novels[1], Quantity = 4, Item= item }
- };
- context.Items.Add(item);
- od.ForEach(o => context.ItemDetails.Add(o));
- context.SaveChanges();
- }
- }
- }