Creating MVC Applications Using Entity Framework Code First Approach

Entity Framework is a relational mapper framework. It is an enhancement of ADO.NET that gives developers an automated mechanism for accessing and storing the data in the database.

Types

  1. Code First
  2. Model First
  3. Database First

Code First

It was introduced in EF 4.1. It is mainly used for domain driven design, i.e., we write our business requirement as models and based on that, EF creates the database.

For creating a database, there are three methods offered by code first approach.

  1. CreateDatabaseIfNotExists
    As the name suggests, if your database does not exist, then it creates that for you.

  2. DropCreateDatabaseIfModelChanges
    Suppose, we have our business logic already and a database is also created on that basis, but we need to change our business models, then we can use this class.

  3. DropCreateDatabaseAlways
    It drops and re-creates the database every time it runs. This approach is helpful for testing purposes. Every time it runs, it seeds some sample data to the database and based on that, we can test our application.

At the time when we extend DbContext to our context class by default, CreateDatabaseIfNotExist method initializes.



If we want to change the initialization process, we can create an initializer class and extend it by encapsulating the same class which extends DbContext class.



Let's see all this with an example for better understanding.



Now, name your project.



Click OK and select Empty template.



This will create a blank MVC 5 project.

Now, start your Package Manager Console by going into Tools -> NuGet Package Manager -> Package Manager Console.



In Package Manger Console, type Install-Package EntityFramework.



This will install Entity Framework's latest stable version.

Now, create your Student Model in Models folder.

  1. using System;  
  2. namespace test.Models  
  3. {  
  4.     public class Student  
  5.     {  
  6.         public int Id { get; set; }  
  7.         public string Name { get; set; }  
  8.         public DateTime DoB { get; set; }  
  9.         public Gender Gender { get; set; }  
  10.         public int Flag { get; set; }  
  11.     }  
  12.     public enum Gender  
  13.     {  
  14.         Male, Female, Other  
  15.     }  
  16. }  
Then, build your solution and add a new folder called Context.

In Context folder, add a class called DatabaseContext and extend DbContext class. This is the main class which implements all Entity Framework functionality.



In Database Context class, write the following code.
  1. using System.Data.Entity;  
  2. using System.Data.Entity.ModelConfiguration.Conventions;  
  3. using test.Models;  
  4. namespace test.Context  
  5. {  
  6.     public class DatabaseContext : DbContext  
  7.     {  
  8.         public DatabaseContext() : base("StudentDatabase")  
  9.         { }  
  10.         public DbSet<Student> Students { get; set; }  
  11.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  12.         {  
  13.             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
  14.         }  
  15.     }  
  16. }  


The parameter accepted by the constructor is our database name. If we are not making any constructor in DatabaseContext class, then the database name will be same as the class name that extends the DbContext class ( DatabaseContext in this case).



This will create a property for Student Entity set.

Note - This code will create a pluralized table name in database and if we want to remove that convention, then we have to override OnModelCreating method in DatabaseContext Class, as shown below.



For seeding the data, when a database is being created, we can override the seed method in initializer class.



The databaseInitializer class inherits (red bordered) one of the three classes offered by entity framework to create database.

Now, register your DatabaseInitializer in Application_Start() method of Global.aspx file.
  1. using test.Context;   
  2. using System.Data.Entity;  
  3. namespace test  
  4. {  
  5.     public class Global : System.Web.HttpApplication  
  6.     {  
  7.         protected void Application_Start(object sender, EventArgs e)  
  8.         {  
  9.             AreaRegistration.RegisterAllAreas();  
  10.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  11.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  12.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  13.             Database.SetInitializer(new DatabaseInitializer());  
  14.         }  
  15.     }  
  16. }  
Add Connection string in web.config file.



Now, build your solution.



Once the solution is built successfully, go to Controller folder and add Controller with Views, using Entity framework.



Name the Controller as StudentController.



Once you add this Controller, Scaffold templates will create all read-write action with views, using Entity Framework. 

Now, go to RouteConfig.cs file to change the default route from Home to Student in App_Start folder and run the application. It will run successfully.





Note - If you want to attach database.mdf file, then add AttachDbFilename=|DataDirectory|\<databaseName>;  to your connection string in web.config file.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now