Introduction
In this article I am not paying much attention to the theory.
This is the continuation of Part 2. If you are new to MVC then I will strongly recommend you to please go through parts one and two before proceeding to this article. Click the following links for the previous parts of this tutorial.
In the last tutorial we saw the basics of Views. We will now discuss the concept of the Model in MVC. A MVC Model is typically a class (of C# or VB.NET). All the views and the controller can access the Model class. The main purpose of the Model class is to communicate to the database and apply validation on that data.
Data access in MVC using Entity Framework
By using the Entity Framework we can communicate with the database in MVC. There are the following three approaches to communicate with a database in Entity Framework.
- Code First Approach
- Database First
- Model First
Code First Approach
As the name suggests, in this approach, we will write the code first to generate the database and in one good day, we will run that code to see the database in the DB server. Here are a few possible scenarios where we can implement the Code First Approach.
- If you are a hard-core developer and always like to play with code then the Code First Approach is fit for you.
- If you want full control over your database design without much knowledge of SQL and a DBA.
- If the application is brand new and is there is no existing database for that application.
In the following example we will go with an Employee and a department table. There is the following procedure you need to follow for the Code First Approach of Entity Framework and then migrate it to a SQL Server database.
Step 1
Open Visual Studio and go to New project under the web tab.
Step 2
Select MVC from the template and click OK.
Step 3
The MVC application solution has been automatically created with some default controller Models and Views. You can delete it or leave as it is.
Then right-click on the Models folder and select Add and select the class then name it Employee.
Now your class is ready with the following code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace CodeFirstApproachWithEmployeesInfo.Models
- {
- public class Employee
- {
-
- }
- }
- Add some properties in Employee class
- public class Employee
- {
- public int Id { get; set; }
- public string EmpName { get; set; }
- public int Salary { get; set; }
- public DateTime EmpDOB { get; set; }
-
- }
This Employee class will represent the Employee table in the database.
Step 4
After adding the Employee Model class add the
EmployeeDBContext class in the same Employee class file. Later the EmployeeDBContext will represent the connection string name of the web.config file. This class name and connection string name must be the same. Inherit the
EmployeeDBContext class from DbContext. For this you need to add the
namespace
using System.Data.Entity.
- public class EmployeeDBContext : DbContext
- {
- public DbSet<Employee> Employees { get; set; }
- }
Now add a property Employees of DbSet<Employee>.
Note: The class named EmployeeDBContext class corresponds to the Entity Framework employee's database context. That is helpful for retrieving, storing and updating the employee class instances in the database. The DbContext class provided by the Entity Framework is the base class of EmployeeDBContext.
Step 5
Add the following connection string inside the web.config file.
- <add name="EmployeeDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\EmployeesDB.mdf;Integrated Security=True" providerName ="System.Data.SqlClient" />
Replace the database file name with yours.
Our connections string is now ready. We will now do CRUD operations with the Employee table.
Step 6
Build the project. Then right-click on the Controllers folder. Select add New Scadffolded Item.
Step 7
Select the MVC tab and select MVC 5 Controller with Views, using Entity Framework and click on Add.
Step 8
Select the Model class as Employee and context class as EmployeeDBContext and click on Add.
Step 9
Now the EmployeesController and CRUD operations view is ready with all the required code. In the following image you can see the views and controller. Open the controller class and take a close look at it.
There will be a method.
-
- public ActionResult Index()
- {
- return View(db.Employees.ToList());
- }
When we run the Index view the first time a database will be created automatically and we will get the following screen.
Click on Create New to add the employee.
When you click the Create button it will automatically redirect to the index view where the employees list will show as in the following:
Now you can click Edit to edit the record, delete to delete the record and so on.
The EmployeeDB is in the SQL Server Express LocalDB since we have specified the SQL Server Express path in our database. So first we migrate this database to a SQL Server database then we will customize the pre-defend template.
SQL Server LocalDB is the data source used by default by Visual Studio. When you work with the Entity Framework Code First Approach, it automatically creates a database, if the database did not exist. You can view it from the "App_Data" folder in the Solution Explorer as we are seeing it in the following image.
Migration in Entity Framework Code FirstWe need to use the following procedure to migrate the database.
Step A
First delete the database in App_Data and build the project. Then use the procedure shown in the following image.
Step B
Type in the following command in the Package Manager Console.
Enable-Migrations -ContextTypeName CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext
And press Enter. You will get the following message as shown in the image.
It creates a "Configurations.cs" file in the new folder (named Migrations folder) in your Solution Explorer.
- namespace CodeFirstApproachWithEmployeesInfo.Migrations
- {
- using System;
- using System.Data.Entity;
- using System.Data.Entity.Migrations;
- using System.Linq;
-
- internal sealed class Configuration : DbMigrationsConfiguration<CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext>
- {
- public Configuration()
- {
- AutomaticMigrationsEnabled = false;
- }
-
- protected override void Seed(CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext context)
- {
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
- }
Step C
The DmployeeDb database has been deleted. Open the Configuration.as and insert a seed value for the employee table using the following code.
- protected override void Seed(CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext context)
- {
-
-
-
-
-
- context.Employees.AddOrUpdate(i=>i.EmpName,
- new Employee
- {
- EmpName = "Manish Kumar",
- Salary= 30000,
- EmpDOB = Convert .ToDateTime ("07/12/1990")
- },
- new Employee
- {
- EmpName = "Namit Kumar",
- Salary= 20000,
- EmpDOB = Convert .ToDateTime ("07/11/1988")
- },
- new Employee
- {
- EmpName = "Vekat Kumar",
- Salary= 25000,
- EmpDOB = Convert .ToDateTime ("07/01/1980")
- }
- );
-
- }
We need to add a Models folder reference here to use the Employee class. The Migration class you created helps to create a database. This is the reason for deleting your database mdf file.
Step D
Now build the project and in the Package Manager Console enter the following command.
add-migration Initial
You will get the following message after the success of the command.
The add-migration Initial command creates a new class file in your Migration folder. The new class named "(DataStamp)_initial.cs code" helps to create a schema for the database. This file's code implements the Employee table in your Employees database.
- public override void Up()
- {
- CreateTable(
- "dbo.Employees",
- c => new
- {
- Id = c.Int(nullable: false, identity: true),
- EmpName = c.String(),
- Salary = c.Int(nullable: false),
- EmpDOB = c.DateTime(nullable: false),
- })
- .PrimaryKey(t => t.Id);
-
- }
-
- public override void Down()
- {
- DropTable("dbo.Employees");
- }
Step E
Enter the following command in your Package Manager Console:
update-database
You will get the following message after the success of the command.
If this results in an error then just check whether or not the local DB was deleted. If not deleted then do the process again.
Then, Migration down Run the program project and see the result.
In the next tutorial we will learn how to edit the table add a new table and apply all the changes to the database and also we will customize the default view generated by the Visual Studio 2013.
Summary
In this illustration you came to understand the basics of the MVC Model and how to communicate with a database using the Entity Framework Code First Approach.
Thanks.
I would like to get feedback from my readers. Please post your feedback, question, or comments about this article.