Introduction
Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database. ORM framework automatically creates classes based on database tables and the opposite is also true; that is, it can also automatically generate necessary SQL to create database tables based on classes.
First we need to install Entity framework and the best way to install that is by using: -NuGet Package Manager.
Code first approach allows us to create our custom classes first and based on those classes entity framework can generate database automatically for us.
Step 1
Create New Project - Select Web Application- Select MVC Template - Cick OK.
Step 2
Go toTools - NuGet Package Manager - Manage NuGet Packages For Solution - Browse and type Entity Framework click on Install
Step 3
Add the following classes in the Model Folder of your project.
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- namespace CodeFirstApproach.Models
- {
- [Table("tblClass")]
- public class Class
- {
- [Key]
- public int ClassID { get; set; }
- public string ClassName { get; set; }
- public List<Student> Students { get; set; }
- public List<Course> Courses { get; set; }
- }
- }
-
-
- [Table("tblStudent")]
- public class Student
- {
- [Key]
- public int StudentID { get; set; }
- public string StudentName { get; set; }
- public Class Class { get; set; }
- }
-
- [Table("tblCourse")]
- public class Course
- {
- [Key]
- public int CourseID { get; set; }
- public string CourseName { get; set; }
- public List<Class> Classes { get; set; }
- }
Step 4
Add another class as a Context Class and add connection string in web.config. In class add DbSet where each DbSet will map to a table in the database. If we have a property DbSet of Students, and the name of that property is Students, the Entity Framework will by default look for a Student table inside the database which in our case is tblStudent as we used [Table("tblStudent")] as Annotation .
- public class StudentContext: DbContext[DBContext maps to a specific database that has a schema that the DBContext understands] {
- public StudentContext(): base("name=conn_StudentDB") {}
- public DbSet < Class > Classes {
- get;
- set;
- }
- public DbSet < Student > Students {
- get;
- set;
- }
- public DbSet < Course > Courses {
- get;
- set;
- }
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder) {
- modelBuilder.Entity < Class > ().HasMany(s => s.Courses).WithMany(c => c.Classes).Map(cs => {
- cs.MapLeftKey("ClassId");
- cs.MapRightKey("CourseId");
- cs.ToTable("tblClassCourse");
- });
- }
- }
Step 4
Add another class as a Context Class and add connection string in web.config.In class add DbSet where each DbSet will map to a table.
Note
We could also say that DBSet class represents an entity set that is used to create, read, update, and delete operations.
Web.Config
In the database, if we have a property DbSet of Students, and the name of that property is Students, the Entity Framework will by default look for an Student table inside the database which in our case is tblStudent as we used [Table("tblStudent")] as Annotation .
- <connectionStrings>
- <add name="conn_StudentDB" connectionString="data source=.;initial catalog=StudentDB;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
- </connectionStrings>
Step 5
In HomeController Index Action write the following code and Run (Press F5)
- public ActionResult Index()
- {
- StudentContext context = new StudentContext();
- var x = (from z in context.Courses select z).ToList();
- return View();
- }
Observation
It will create the database with all the tables.
Point to Start
Another Approach is Code Based Migration - Drop the database and follow the step below.
Step 1
Entity Framework Code First Migration
Go To Package Manager Console and type ,
PM> Enable-Migrations
Note
It will create a Configuration file in the Migration Folder.
Step 2
PM> Add-Migration -Name CreateDb
Note
It will create a Script in the Migration Folder with xxx_CreateDb.cs. It will consist of two methods, Up() and Down().
- public partial class CreateDb: DbMigration {
- public override void Up() {
-
- }
- public override void Down() {
-
- }
- }
Step3 - PM> Update-Database
We will see our Database getting created once again just like the image above.
Currently we have no data. Insert a few records in the following table.
- insert into [dbo].[tblClass] values('Computer Science'),('Electronics And Communication'),('Mechanical')
- insert into [dbo].[tblStudent]values('Zeko',1),('Priyanka',2),('Sumit',3),('Aniket',1),('Surya',2),('Deepak',3)
- insert into [dbo].[tblCourse] values('.Net'),('SQL'),('Java'),('VLSI'),('Analog Communication'),('Optical Fiber Communication'),('Thermodynamics'),('Measurement and Instructions'),('Advanced Solid Mechanics')
- insert into [dbo].[tblClassCourse] values(1,1),(1,2),(1,3),(2,4),(2,5),(2,6),(2,3),(3,7),(3,8),(3,9),(3,3),(1,5),(3,5);
Updating Table
Step 1
Now we will add a property in Student class PhoneNo
- [Table("tblStudent")]
- public class Student {
- public int StudentID {
- get;
- set;
- }
- public string StudentName {
- get;
- set;
- }
- [Required]
- public string PhoneNo {
- get;
- set;
- }
- public Class Class {
- get;
- set;
- }
- }
Step 2
Go to Console and Add-Migration again for the changes in our model which will create _AddedProperty_tblStudent.cs inside the configuration folder.
PM> Add-Migration -Name AddedProperty_tblStudent
- public partial class AddedProperty_tblStudent: DbMigration {
- public override void Up() {
- AddColumn("dbo.tblStudent", "PhoneNo", c => c.String(nullable: false));
-
-
-
- }
- public override void Down() {
- DropColumn("dbo.tblStudent", "PhoneNo");
- }
- }
Step 3
PM> Update-Database. Check the following changes in DB for tblStudent.
RollBack - Update-Database -TargetMigration:"CreateDb"
Happy Learning...