In this ASP.NET MVC Tutorial, we are going to see a simple but practical implementation for Entity Framework Code First Approach. We have already given examples on Entity Framework Model First as well as traditional Database First approaches in other examples. You can follow other sample implementations at below given URLs.
While using Code-First Approach, we start with creating classes in code first as per our domain requirements instead of doing database design(the traditional way). On the basis of our classes and provided configuration, Code-First APIs will create the database on the fly.
So, for the sake of this implementation, we will start by writing C# code (creating C# classes for domain as well as context classes). When the application will run, Code First APIs will create the new database (if it does not exist yet) and map classes with the database using default code-first conventions.
Entity Framework Code First Approach
Following are the steps we can follow for Entity Framework Code First Approach:
Create visual studio project “Entity_Framework_FAQ”.Image may be NSFW.
Clik here to view.
On next screen choose template as MVC.Image may be NSFW.
Clik here to view.
Click “OK”, Your application will be created and you get following welcome screen:Image may be NSFW.
Clik here to view.
If you have not installed Entity Framework, please install it by using Nuget Package Console Command as follows:
Install-Package EntityFramework -Version 6.1.1
Or follow the link to Install Entity Framework in Visual Studio using step by step approach.
In Code-First approach, Instead of designing database tables first, classes are created first.
- Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer]
28 Lectures, 2.5 Hours Video, Intermediate Level
Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms. - AngularJS for ASP.NET MVC Developers [Brett Romero]
10 Lectures, 1 hour video, Intermediate Level
The Fastest Way For .NET Developers To Add AngularJS To Their Resume - ASP.NET with Entity Framework from Scratch
[Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
Latest approach of web application development - Comprehensive ASP.NET MVC [3D BUZZ]
34 lectures, 14 Hours Video, All Levels
From zero knowledge of ASP.NET to deploying a complete project to production.
Create class “Category.cs” as shown below:Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Add following code in “Category.cs” as shown below:
public class Category { public int CategoryId { get; set; } public string CategoryName { get; set; } public ICollection<Product> Products { get; set; } }
Similarly add product class and add following code to it:
public class Product { public int ProductId { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } public int CategoryId { get; set; } public virtual Category category { get; set; } }
Add a data context class that will contain the category model and product model:
It will contain following code:
public class EF_FAQ_Entities : DbContext { public DbSet<Category> Categories { get; set;} public DbSet<Product> Products { get; set; } }
Add new Controller “Products” as shown in below steps:Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
After click on “Add” button, the scaffolding technique will put all the necessary code in the respective controller and related views.
Product Controller will contain following code:
public class ProductsController : Controller { private EF_FAQ_Entities db = new EF_FAQ_Entities(); // GET: Products public ActionResult Index() { var products = db.Products.Include(p => p.category); return View(products.ToList()); } // GET: Products/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Product product = db.Products.Find(id); if (product == null) { return HttpNotFound(); } return View(product); } // GET: Products/Create public ActionResult Create() { ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName"); return View(); } // POST: Products/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ProductId,ProductName,Price,CategoryId")] Product product) { if (ModelState.IsValid) { db.Products.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId); return View(product); } // GET: Products/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Product product = db.Products.Find(id); if (product == null) { return HttpNotFound(); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId); return View(product); } // POST: Products/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ProductId,ProductName,Price,CategoryId")] Product product) { if (ModelState.IsValid) { db.Entry(product).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId); return View(product); } // GET: Products/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Product product = db.Products.Find(id); if (product == null) { return HttpNotFound(); } return View(product); } // POST: Products/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Product product = db.Products.Find(id); db.Products.Remove(product); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
Similarly add “Categories” controller. Categories controller will contain following code:
public class CategoriesController : Controller { private EF_FAQ_Entities db = new EF_FAQ_Entities(); // GET: Categories public ActionResult Index() { return View(db.Categories.ToList()); } // GET: Categories/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Category category = db.Categories.Find(id); if (category == null) { return HttpNotFound(); } return View(category); } // GET: Categories/Create public ActionResult Create() { return View(); } // POST: Categories/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "CategoryId,CategoryName")] Category category) { if (ModelState.IsValid) { db.Categories.Add(category); db.SaveChanges(); return RedirectToAction("Index"); } return View(category); } // GET: Categories/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Category category = db.Categories.Find(id); if (category == null) { return HttpNotFound(); } return View(category); } // POST: Categories/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "CategoryId,CategoryName")] Category category) { if (ModelState.IsValid) { db.Entry(category).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(category); } // GET: Categories/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Category category = db.Categories.Find(id); if (category == null) { return HttpNotFound(); } return View(category); } // POST: Categories/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Category category = db.Categories.Find(id); db.Categories.Remove(category); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
Put connection string in web.config as:
<connectionStrings> <add name="EF_FAQ_Entities" connectionString="Data Source=YourSQLInstanceName;Initial Catalog=EF_FAQ;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings>
When you run the application and access “/categories”, it will automatically create the database same as the name of Context class i.e.Image may be NSFW.
Clik here to view.
While accessing the url ”Categories”, following screen will appear:Image may be NSFW.
Clik here to view.
Click on create new, to create new category.
Image may be NSFW.
Clik here to view.
After creation of categories, let’s create products.
Access “/Products”, following screen will appear,Image may be NSFW.
Clik here to view.
Create new product,Image may be NSFW.
Clik here to view.
This is very basic example for ASP.NET MVC Application with Code-First Approach using two related entities i.e. Category & Product. Hopefully, it will be helpful for understanding the approach in a more practical way.
- A. System Error
- B. It accepts new values
- C. Compiler error
- D. Throws ConstraintException
To further test your ASP.NET MVC/EF skill, Take a Complete FREE Online Test or MCSD Practice Exam: 70-486 (Developing ASP.NET MVC Web Applications). Simply Click Here.
Further If you are going to appear for a Technical Interview on EF, you can get below a comprehensive list of Entity Framework Interview Questions and Detailed answers for beginners as well as advanced concepts.
- Entity Framework Interview Questions/Frequently Asked Questions (FAQs)
- ASP.NET MVC Interview Questions/Frequently Asked Questions (FAQs)
- What’s new in Entity Framework from beginning to EF7 – EF Core
- Bootstrap Interview Questions/Frequently Asked Questions (FAQs)
- AngularJS Interview Questions/Frequently Asked Questions (FAQs)
- jQuery Interview Questions/Frequently Asked Questions (FAQs)
Correct Answer: D
The post ASP.NET MVC Application with EF6 Code First Approach appeared first on Web Development Tutorial.