MVC Entity Framework Code First - Step 3

In MVC, Entity Framework Code First Model is good fit and easy to use. In this case we don't need to create our model separately. Whatever the model we created in our previous article is enough to create the table for category which we are going to achieve in this article and maney more. We will learn how to use Entity Framework with code first, how to decorate properties of table, property data type, validation for required fields, length of field etc.

See how to set and use entity framework. If you don't want to watch that video then install Entity Framework by opening

  • View Menu
  • Other Windows
  • Package Manager Console
  • Type: Install-Package EntityFramework -Version 6.1.2

Now open the web.config file and check the connection string, it will look like

 <add name="DefaultConnection" 
    connectionString="Data Source=(LocalDb)\v11.0;
    AttachDbFilename=|DataDirectory|\Learning.mdf;
    Initial Catalog=Learning;
    Integrated Security=True"
    providerName="System.Data.SqlClient" />

By default AttachDbFilename and Initial Catalog value will be the application name with some random number which I changed to Learning because I want my database name to be Learning.

We will keep all the database related files into a separate folder so create a new folder "Data" on the root. Create a new class in it, named LearningContext which will derive from DbContext. For using DbContext we need to add using System.Data.Entity;. We can also add the using in different ways like put the cursor on DbContext and press CTRL + . (dot) or right click on it and select resolve.

public class LearningContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
}

Now change the action method in controller, it will look like this

public ActionResult Index()
{
    var db = new LearningContext();
    var categories = db.Categories;
    return View(categories);
}

We have created an object of our newly created data context (var db = new LearningContext();) and try to get the data from database.

Run the application and try to open the /category/index page. We will see a blank page because we don't have any record in it, good thing is that our database is created. Add a new class LearningContextInitializer.cs into our data folder and add following lines into it

Now we will create a separate class to add some values into table while creating the database because we will need to re-create the database again and again after updating existing table or adding new tables into it.

public class LearningContextInitializer : DropCreateDatabaseIfModelChanges<LearningContext>
{
    protected override void Seed(LearningContext context)
    {
        var categories = new List<Category>
       {
          new Category { CategoryId = 1, CategoryName =  "Laptop" },
          new Category { CategoryId = 1, CategoryName = "Software" },
          new Category { CategoryId = 1, CategoryName = "Accessories" }
       };

        // add data into table and save to db
        foreach (var category in categories)
        {
          context.Categories.Add(category);
        }
        context.SaveChanges();
    }
}

How it will be called, let's add one line to glabla.ascs file in Application_Start method

Database.SetInitializer(new LearningContextInitializer());

If you will run the application it will not insert these records because we are using DropCreateDatabaseIfModelChanges, which meand database will drop and create only when there is any change. To do so add one more property with our Category model class

[Display(Name = "Is Active")]
public bool IsActive { get; set; } 

Now run the application and we will see those records will be there. Check the database and we will see all these records will be available into it.

Now we will create one more model class Product which we will use latter on. We will create a very simple product table only with id, name, price and categoryId, we will not use relationship for now between tables.

public class Product
{
    public Int32 ProductId { get; set; }

    [Required]
    [Display(Name="Product Name")]
    public String ProductName { get; set; }

    [Required]
    [Display(Name = "Price")]
    public Decimal Price { get; set; }

    [Required]
    [Display(Name = "Category")]
    public Int32 CategoryId { get; set; }
}

After adding the mode we need to add the class in our LearningContext, so our context class will be:

public class LearningContext : DbContext
{
    public DbSet<Category> Categories { get; set; }

    public DbSet<Product> Products { get; set; }
}

Let's add some records in this table as well, it is not mandatory but will help to test it. Open our initialiser table and add these lines to that and now it will look like this

using Advance.Learning.WebApp.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Advance.Learning.WebApp.Data
{
  public class LearningContextInitializer : DropCreateDatabaseIfModelChanges<LearningContext>
  {
    protected override void Seed(LearningContext context)
    {
      // Add records into Category table
      var categories = new List<Category>
      {
        new Category { CategoryId = 1, CategoryName =  "Laptop", IsActive =true },
        new Category { CategoryId = 2, CategoryName = "Software", IsActive =true },
        new Category { CategoryId = 3, CategoryName = "Accessories", IsActive =true }
      };

      // add data into table and save to db
      foreach (var category in categories)
      {
        context.Categories.Add(category);
      }
      context.SaveChanges();

      // Add records into Product table 
      var products = new List<Product>
      {
        new Product{ProductId = 1, ProductName = "Dell Inspiron", Price = 750, CategoryId =1 },
        new Product{ProductId = 2, ProductName = "Dell Chromebook", Price = 875, CategoryId =1 },
        new Product{ProductId = 3, ProductName = "Lenovo Yoga Pro 2", Price = 1000, CategoryId =1 },
        new Product{ProductId = 4, ProductName = "Lenovo Yoga Pro 2 Ultrabook", Price = 1175, CategoryId =1 },

        new Product{ProductId = 5, ProductName = "Office 365", Price = 175, CategoryId =2 },
        new Product{ProductId = 6, ProductName = "Windows 8", Price = 550, CategoryId =2 },
        new Product{ProductId = 7, ProductName = "Nortan Antivirus", Price = 200, CategoryId =2 },
        new Product{ProductId = 8, ProductName = "Visual Studio 2013", Price = 905, CategoryId =2 },

        new Product{ProductId = 10, ProductName = "Logistic Keyboard", Price = 36, CategoryId =3 },
        new Product{ProductId = 9, ProductName = "IBM Mouse", Price = 22, CategoryId =3 },
        new Product{ProductId = 9, ProductName = "Laptop Screen Guard", Price = 30, CategoryId =3 },
        new Product{ProductId = 9, ProductName = "Mini HDMI Cod", Price = 37, CategoryId =3 }
      };

      // add data into table and save to db
      foreach (var product in products)
      {
        context.Products.Add(product);
      }
      context.SaveChanges();
    }
  }
}

Now run the application and open the category page, if you have open the database close it because it will try to delete and create new database. One more thing I need to point, until or unless we will try to use the database it will not delete and create new one, that's why I said to open the category page.

Now open the database and see it will have two tables one Category and other Product, in our next article we will use these tables to insert, update and delete categories.



Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • entity-framework
By Ali Adravi On 28 Feb, 15  Viewed: 2,903

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 40,117

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 105,947

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 3,738

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 6,997

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 25,493