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 :-) .
Ad

More Related Content

What's hot (20)

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

Viewers also liked (8)

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

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

LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
Sadhana Sreekanth
 
ASP.NET MVC Introduction
ASP.NET MVC IntroductionASP.NET MVC Introduction
ASP.NET MVC Introduction
Sumit Chhabra
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
Oop c sharp_part_1
Oop c sharp_part_1Oop c sharp_part_1
Oop c sharp_part_1
shivaksn
 
Ef code first
Ef code firstEf code first
Ef code first
ZealousysDev
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
Entity frameworks101
Entity frameworks101Entity frameworks101
Entity frameworks101
Rich Helton
 
How to create fast and much more efficient database
How to create fast and much more efficient databaseHow to create fast and much more efficient database
How to create fast and much more efficient database
shivang tyagi
 
C# interview
C# interviewC# interview
C# interview
ajeesharakkal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
FaRid Adwa
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
Building richwebapplicationsusingasp
Building richwebapplicationsusingaspBuilding richwebapplicationsusingasp
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
sonia merchant
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET Attributes
Pooja Gaikwad
 
IntroductionToMVC
IntroductionToMVCIntroductionToMVC
IntroductionToMVC
Akhil Mittal
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Bill Buchan
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
ASP.NET MVC Introduction
ASP.NET MVC IntroductionASP.NET MVC Introduction
ASP.NET MVC Introduction
Sumit Chhabra
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
Oop c sharp_part_1
Oop c sharp_part_1Oop c sharp_part_1
Oop c sharp_part_1
shivaksn
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
Entity frameworks101
Entity frameworks101Entity frameworks101
Entity frameworks101
Rich Helton
 
How to create fast and much more efficient database
How to create fast and much more efficient databaseHow to create fast and much more efficient database
How to create fast and much more efficient database
shivang tyagi
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
FaRid Adwa
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
sonia merchant
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET Attributes
Pooja Gaikwad
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Bill Buchan
 
Ad

More from Akhil Mittal (20)

PDFArticle
PDFArticlePDFArticle
PDFArticle
Akhil Mittal
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
Akhil Mittal
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
Akhil Mittal
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
Akhil Mittal
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
Akhil Mittal
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
Akhil Mittal
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
Akhil Mittal
 
RESTfulDay9
RESTfulDay9RESTfulDay9
RESTfulDay9
Akhil Mittal
 
PDF_Article
PDF_ArticlePDF_Article
PDF_Article
Akhil Mittal
 
RESTful Day 7
RESTful Day 7RESTful Day 7
RESTful Day 7
Akhil Mittal
 
RESTful Day 6
RESTful Day 6RESTful Day 6
RESTful Day 6
Akhil Mittal
 
RESTful Day 5
RESTful Day 5RESTful Day 5
RESTful Day 5
Akhil Mittal
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
Akhil Mittal
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questions
Akhil Mittal
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
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
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
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 ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
Akhil Mittal
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Akhil Mittal
 
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Akhil Mittal
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
Akhil Mittal
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
Akhil Mittal
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
Akhil Mittal
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
Akhil Mittal
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
Akhil Mittal
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
Akhil Mittal
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
Akhil Mittal
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questions
Akhil Mittal
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
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
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
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 ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
Akhil Mittal
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Akhil Mittal
 
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
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 :-) .