SlideShare a Scribd company logo
Learning MVC : Part4
MVC Application using EntityFrameworkCode-First approach.
Introduction:
In our firstthree articles, we learnt a lot about MVC, starting fromdefinition to use, fromcreating an application to connecting
the MVC application with databaseusing different techniques.
In very last partof the series we learnt how to connect our MVC application with existing databaseusing Entity Framework.
Our this article will focus on connecting our MVC application with database using CodeFirstapproach i.e. one of the feature
Microsoft’s Entity Framework provides.
Our Roadmap:
Just to remind our full roadmap towards learning MVC,
Part1: Introduction to MVC architecture and Separation of Concerns.
Part 2: Creating MVC Application from scratch and connecting it with databaseusing LINQ to SQL.
Part 3: Connecting the MVC Application with the help of EntityFramework DB-Firstapproach.
Part 4: Connecting the MVC Applicationwiththe helpof EntityFramework Code-Firstapproach.
Part 5: Implementing Repository Pattern in MVC Application with EntityFramework.
Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVCApplication with EntityFramework.
Pre-requisites:
There are few pre-requisites beforewe start with the article,
1. We haverunning sample application that we created in third part of the article series.
2. We haveEntityFramework 4.1 packageor dll on our local file system.
3. We understand how MVCapplication is created.
Code-First Approach:
To achieve a domain driven design, Entity Framework introduced EF 4.1 Code First. In the CodeFirst approach, wefocus on
the domain design or entities/POCO classes first and create classes as per our model requirement. We do not have the
database of the application, rather wecreate databaseautomatically fromcode after defining our domain.The database
created perfectly matches with the domain we design, so we have to be very conscious and keen in designing our domain
model. Itfeels exciting to see databasecreated on the fly with the help of our entities and xml configuration, withouteven
opening databaseserver.
No matter, you arenot an expert in database, if you are a c# developer, justfocus on your model/class creation.
EntityFramework willtake headache of creating and managing databasefor you.
Procedure:
Step1: Open the MVCapplication that we created in Learning MVC-Part3 in your VisualStudio.
We can clearly see and remember whatwe used to connect our MVC application to databasewith the help of entity
framework, yes itwas edmx class and our Model.tt classes generated fromedmx classes.
Step2: We don’tneed existing data-base, so you can delete the already created database for our part 3 application (if
created).
Step3: We don’tneed edmx files now, so let’s clean our application, wipe out all these classes.Justdelete EFDataModel.edmx,
Model1.Context.tt and Model1.tt file. Now please do not run the application  , it will givecompile time errors , since we
were using those classes ;-), Our Solution will look like,
Our old solution had UserListclass in Models folder, I have only changed the name of the class for differentiating it with
previous application, and readability as was in firstpart.
Step4: As simple as that, justadd a class to your solution, and name it MVCDBContext.cs as shown in following image,
Step5: Justadd System.Data.Entity dll as a reference to the solution if not already added.
Step6: Usethe namespaceSystem.Data.Entity in our DBContext class, and inherit the added class fromDBContext class,
DbContext Class: According to msdn , DbContext class is conceptually similar to ObjectContext.To define,the
ObjectContext class is the part of the core EF API in the Microsoft.NET Framework 4 and this is our hero class that allows us to
performqueries, change tracking and update the databaseusing the strongly typed classes that represent our model(entity
class). The DbContext is a wrapper around ObjectContextthat exposes the most commonly used features of ObjectContext as
well as provides somesimpler “shortcuts” to tasks that are frequently used but complicated to code directly with
ObjectContext.Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific
model.
Step7: Add a DBSet property to the DbContext class that we created,
public DbSet<User> Users { get; set; }
User, defined in angular brackets, is the model that we created in Models folder, so our MVCDBContext class looks like,
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using LearningMVC.Models;
namespace LearningMVC
{
public class MVCDBContext : DbContext
{
public DbSet<User> Users { get; set; }
}
}
That’s it, our 90% work is done .
DbSet property: It is a Simplified alternative to ObjectSetand is used to performCRUD operations against a specific type
fromthe model.
By default name of the DbContext class will be the name our databasethat will automatically be created, so be wiseto select
the name of context class, else it could be handled in web.config also.
The name of model will be the name of Table in database and properties of model will be the columns of the table.
Our Heroes:
Both DbContext and DbSet are our super heroes, in creating and dealing with databaseoperations, and make us far
abstracted, providing ease of useto us.
When we are working with DbContext, weare in real working with entity sets. DbSetrepresents a typed entity set that is used
to performcreate, read, update, and delete operations. We are not creating DbSetobjects and using them indepedently.
DbSet can be only used with DbContext.
Step8: Define a connection string in web.config file, you can removepreviously defined connection string,th new connection
string will somewhatlook like,
The name of the connection string will be the name of the DbContect that we defined , i.e. MVCDbContext.
Step8: Now we justhave to modify the access method in controllers,earlier, when we created application in third part, we
were accessing the context class fromthe modelcontext class that were generated fromedmx file.Edmx file was added having
reference to already created database.
But now the case is different, we don’t havea databasenow, we’ll access the table and columns using our MVCDBContext
class in controllers, so justchange following line of code used in Actions of earlier application,
var dbContext = new MVCEntities() ;
to
var dbContext = new MVCDBContext();
Job Done.
Just Hit F5, and You’ll see,
How does the application run, whereis the data base??? Dude, go back to your data base server, and check for database,
We see our data baseis created, with the name MVCDB, that’s the magic of EntityFramework.Nowwecan performall the
CRUD operations on this database, using our application. Justcreate a new user.
In databasewe see, user created.
By default, integer propert with ID in its name of model will be the primary key in the data base, in our caseUserId,or you can
define the primary key in the model too.
Conclusion:
Now we know how to play with EntityFramework to create databaseas per our domain model fromour code,wehave already
moved ahead to advanced concepts of MVC and Entity Framework.
When we see the definition of DbContext, it uses the terms Repository Pattern and Unit of Work Pattern,We’lldiscuss these
more in detail in my next article.
Happy Coding :-) .

More Related Content

What's hot (20)

PDF
Introduction to JDBC and JDBC Drivers
Kumar
 
PDF
Large-Scale JavaScript Development
Addy Osmani
 
PPTX
Spring framework DAO
Anuj Singh Rajput
 
PPTX
Spring database - part2
Santosh Kumar Kar
 
PPTX
Windows Azure
Farhad Idrees MCEP MCE MCD
 
PPTX
Spring jdbc dao
Anuj Singh Rajput
 
PPS
Jdbc api
kamal kotecha
 
PDF
IRJET- Lightweight MVC Framework in PHP
IRJET Journal
 
PPTX
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
DOCX
Struts notes
Rajeev Uppala
 
PDF
Learn about dot net attributes
sonia merchant
 
ODT
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
DOC
Dot net interview questions
Netra Wable
 
PPT
java jdbc connection
Waheed Warraich
 
DOCX
TY.BSc.IT Java QB U3
Lokesh Singrol
 
PDF
Jdbc 1
Mukesh Tekwani
 
PPT
Dealing with SQL Security from ADO.NET
Fernando G. Guerrero
 
PPTX
KnockOutjs from Scratch
Udaya Kumar
 
PDF
Flex3 data binding
guestdf3003
 
PDF
Advance Java Practical file
varun arora
 
Introduction to JDBC and JDBC Drivers
Kumar
 
Large-Scale JavaScript Development
Addy Osmani
 
Spring framework DAO
Anuj Singh Rajput
 
Spring database - part2
Santosh Kumar Kar
 
Spring jdbc dao
Anuj Singh Rajput
 
Jdbc api
kamal kotecha
 
IRJET- Lightweight MVC Framework in PHP
IRJET Journal
 
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
Struts notes
Rajeev Uppala
 
Learn about dot net attributes
sonia merchant
 
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
Dot net interview questions
Netra Wable
 
java jdbc connection
Waheed Warraich
 
TY.BSc.IT Java QB U3
Lokesh Singrol
 
Dealing with SQL Security from ADO.NET
Fernando G. Guerrero
 
KnockOutjs from Scratch
Udaya Kumar
 
Flex3 data binding
guestdf3003
 
Advance Java Practical file
varun arora
 

Viewers also liked (8)

PDF
Learn ASP.NET Core 1.0, MVC 6, Web APIs & EF - Bonus iOS App
ayman diab
 
PPT
Document Management System
Som Imaging Informatics Pvt. Ltd
 
PPTX
MVC for Desktop Application - Part 1
晟 沈
 
PPTX
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
PPT
Document Management System(DMS)
Nishant Shah
 
PPTX
Document management system
Raghu Raja
 
PPT
Document Management With Workflow Presentation
John Street
 
PPTX
Document Management System (DMS)
Hiran Wickramainghe
 
Learn ASP.NET Core 1.0, MVC 6, Web APIs & EF - Bonus iOS App
ayman diab
 
Document Management System
Som Imaging Informatics Pvt. Ltd
 
MVC for Desktop Application - Part 1
晟 沈
 
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
Document Management System(DMS)
Nishant Shah
 
Document management system
Raghu Raja
 
Document Management With Workflow Presentation
John Street
 
Document Management System (DMS)
Hiran Wickramainghe
 
Ad

Similar to MVC Application using EntityFramework Code-First approach Part4 (20)

PPTX
Entity Framework Database and Code First
James Johnson
 
PPTX
La sql
James Johnson
 
PDF
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
DOCX
LearningMVCWithLINQToSQL
Akhil Mittal
 
PPTX
MVC and Entity Framework 4
James Johnson
 
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
PPTX
ASP.NET MVC and Entity Framework 4
James Johnson
 
PDF
Intake 37 ef2
Mahmoud Ouf
 
PDF
Intake 38 data access 5
Mahmoud Ouf
 
PPTX
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
PDF
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
PPTX
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
PDF
Murach': HOW TO DEVELOP A DATA DRIVEN MVC WEB
MahmoudOHassouna
 
PPTX
MVC and Entity Framework
James Johnson
 
PPT
AspMVC4 start101
Rich Helton
 
PPT
Overview of CSharp MVC3 and EF4
Rich Helton
 
PPTX
Getting started with entity framework
Lushanthan Sivaneasharajah
 
PPTX
MVC and Entity Framework 4
James Johnson
 
PPTX
Ef code first
ZealousysDev
 
PPTX
Entity framework code first
Confiz
 
Entity Framework Database and Code First
James Johnson
 
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
LearningMVCWithLINQToSQL
Akhil Mittal
 
MVC and Entity Framework 4
James Johnson
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
ASP.NET MVC and Entity Framework 4
James Johnson
 
Intake 37 ef2
Mahmoud Ouf
 
Intake 38 data access 5
Mahmoud Ouf
 
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
Murach': HOW TO DEVELOP A DATA DRIVEN MVC WEB
MahmoudOHassouna
 
MVC and Entity Framework
James Johnson
 
AspMVC4 start101
Rich Helton
 
Overview of CSharp MVC3 and EF4
Rich Helton
 
Getting started with entity framework
Lushanthan Sivaneasharajah
 
MVC and Entity Framework 4
James Johnson
 
Ef code first
ZealousysDev
 
Entity framework code first
Confiz
 
Ad

More from Akhil Mittal (20)

PDF
PDFArticle
Akhil Mittal
 
PDF
Diving into VS 2015 Day5
Akhil Mittal
 
PDF
Diving into VS 2015 Day4
Akhil Mittal
 
PDF
Diving into VS 2015 Day3
Akhil Mittal
 
PDF
Diving into VS 2015 Day2
Akhil Mittal
 
PDF
Diving into VS 2015 Day1
Akhil Mittal
 
PDF
Agile Release Planning
Akhil Mittal
 
PDF
RESTfulDay9
Akhil Mittal
 
PDF
PDF_Article
Akhil Mittal
 
PDF
RESTful Day 7
Akhil Mittal
 
PDF
RESTful Day 6
Akhil Mittal
 
DOCX
IntroductionToMVC
Akhil Mittal
 
PDF
RESTful Day 5
Akhil Mittal
 
PDF
C sharp and asp.net interview questions
Akhil Mittal
 
PDF
Asp.net interview questions
Akhil Mittal
 
PDF
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
PDF
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Akhil Mittal
 
PDF
Resolve dependency of dependencies using Inversion of Control and dependency ...
Akhil Mittal
 
PDF
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
PDF
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 
PDFArticle
Akhil Mittal
 
Diving into VS 2015 Day5
Akhil Mittal
 
Diving into VS 2015 Day4
Akhil Mittal
 
Diving into VS 2015 Day3
Akhil Mittal
 
Diving into VS 2015 Day2
Akhil Mittal
 
Diving into VS 2015 Day1
Akhil Mittal
 
Agile Release Planning
Akhil Mittal
 
RESTfulDay9
Akhil Mittal
 
PDF_Article
Akhil Mittal
 
RESTful Day 7
Akhil Mittal
 
RESTful Day 6
Akhil Mittal
 
IntroductionToMVC
Akhil Mittal
 
RESTful Day 5
Akhil Mittal
 
C sharp and asp.net interview questions
Akhil Mittal
 
Asp.net interview questions
Akhil Mittal
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Akhil Mittal
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Akhil Mittal
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 

MVC Application using EntityFramework Code-First approach Part4

  • 1. Learning MVC : Part4 MVC Application using EntityFrameworkCode-First approach. Introduction: In our firstthree articles, we learnt a lot about MVC, starting fromdefinition to use, fromcreating an application to connecting the MVC application with databaseusing different techniques. In very last partof the series we learnt how to connect our MVC application with existing databaseusing Entity Framework. Our this article will focus on connecting our MVC application with database using CodeFirstapproach i.e. one of the feature Microsoft’s Entity Framework provides. Our Roadmap: Just to remind our full roadmap towards learning MVC, Part1: Introduction to MVC architecture and Separation of Concerns. Part 2: Creating MVC Application from scratch and connecting it with databaseusing LINQ to SQL. Part 3: Connecting the MVC Application with the help of EntityFramework DB-Firstapproach. Part 4: Connecting the MVC Applicationwiththe helpof EntityFramework Code-Firstapproach. Part 5: Implementing Repository Pattern in MVC Application with EntityFramework. Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVCApplication with EntityFramework. Pre-requisites: There are few pre-requisites beforewe start with the article, 1. We haverunning sample application that we created in third part of the article series. 2. We haveEntityFramework 4.1 packageor dll on our local file system. 3. We understand how MVCapplication is created.
  • 2. Code-First Approach: To achieve a domain driven design, Entity Framework introduced EF 4.1 Code First. In the CodeFirst approach, wefocus on the domain design or entities/POCO classes first and create classes as per our model requirement. We do not have the database of the application, rather wecreate databaseautomatically fromcode after defining our domain.The database created perfectly matches with the domain we design, so we have to be very conscious and keen in designing our domain model. Itfeels exciting to see databasecreated on the fly with the help of our entities and xml configuration, withouteven opening databaseserver. No matter, you arenot an expert in database, if you are a c# developer, justfocus on your model/class creation. EntityFramework willtake headache of creating and managing databasefor you. Procedure: Step1: Open the MVCapplication that we created in Learning MVC-Part3 in your VisualStudio.
  • 3. We can clearly see and remember whatwe used to connect our MVC application to databasewith the help of entity framework, yes itwas edmx class and our Model.tt classes generated fromedmx classes. Step2: We don’tneed existing data-base, so you can delete the already created database for our part 3 application (if created).
  • 4. Step3: We don’tneed edmx files now, so let’s clean our application, wipe out all these classes.Justdelete EFDataModel.edmx, Model1.Context.tt and Model1.tt file. Now please do not run the application  , it will givecompile time errors , since we were using those classes ;-), Our Solution will look like, Our old solution had UserListclass in Models folder, I have only changed the name of the class for differentiating it with previous application, and readability as was in firstpart.
  • 5. Step4: As simple as that, justadd a class to your solution, and name it MVCDBContext.cs as shown in following image, Step5: Justadd System.Data.Entity dll as a reference to the solution if not already added. Step6: Usethe namespaceSystem.Data.Entity in our DBContext class, and inherit the added class fromDBContext class,
  • 6. DbContext Class: According to msdn , DbContext class is conceptually similar to ObjectContext.To define,the ObjectContext class is the part of the core EF API in the Microsoft.NET Framework 4 and this is our hero class that allows us to performqueries, change tracking and update the databaseusing the strongly typed classes that represent our model(entity class). The DbContext is a wrapper around ObjectContextthat exposes the most commonly used features of ObjectContext as well as provides somesimpler “shortcuts” to tasks that are frequently used but complicated to code directly with
  • 7. ObjectContext.Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model. Step7: Add a DBSet property to the DbContext class that we created, public DbSet<User> Users { get; set; } User, defined in angular brackets, is the model that we created in Models folder, so our MVCDBContext class looks like, using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using LearningMVC.Models; namespace LearningMVC { public class MVCDBContext : DbContext { public DbSet<User> Users { get; set; } } } That’s it, our 90% work is done . DbSet property: It is a Simplified alternative to ObjectSetand is used to performCRUD operations against a specific type fromthe model. By default name of the DbContext class will be the name our databasethat will automatically be created, so be wiseto select the name of context class, else it could be handled in web.config also. The name of model will be the name of Table in database and properties of model will be the columns of the table. Our Heroes:
  • 8. Both DbContext and DbSet are our super heroes, in creating and dealing with databaseoperations, and make us far abstracted, providing ease of useto us. When we are working with DbContext, weare in real working with entity sets. DbSetrepresents a typed entity set that is used to performcreate, read, update, and delete operations. We are not creating DbSetobjects and using them indepedently. DbSet can be only used with DbContext. Step8: Define a connection string in web.config file, you can removepreviously defined connection string,th new connection string will somewhatlook like,
  • 9. The name of the connection string will be the name of the DbContect that we defined , i.e. MVCDbContext. Step8: Now we justhave to modify the access method in controllers,earlier, when we created application in third part, we were accessing the context class fromthe modelcontext class that were generated fromedmx file.Edmx file was added having reference to already created database. But now the case is different, we don’t havea databasenow, we’ll access the table and columns using our MVCDBContext class in controllers, so justchange following line of code used in Actions of earlier application,
  • 10. var dbContext = new MVCEntities() ; to var dbContext = new MVCDBContext(); Job Done. Just Hit F5, and You’ll see, How does the application run, whereis the data base??? Dude, go back to your data base server, and check for database,
  • 11. We see our data baseis created, with the name MVCDB, that’s the magic of EntityFramework.Nowwecan performall the CRUD operations on this database, using our application. Justcreate a new user.
  • 12. In databasewe see, user created.
  • 13. By default, integer propert with ID in its name of model will be the primary key in the data base, in our caseUserId,or you can define the primary key in the model too. Conclusion: Now we know how to play with EntityFramework to create databaseas per our domain model fromour code,wehave already moved ahead to advanced concepts of MVC and Entity Framework.
  • 14. When we see the definition of DbContext, it uses the terms Repository Pattern and Unit of Work Pattern,We’lldiscuss these more in detail in my next article. Happy Coding :-) .