SlideShare a Scribd company logo
ASP.NET MVC and Entity FrameworkUtah Code CampSaturday, September 25, 2010James JohnsonTechnical Evangelist
Technical Evangelist with ComponentOneFounder and President of the Inland Empire .NET User’s GroupMicrosoft MVPBut I don’t consider myself an expert. I just love to playADHD/ADD/OCD when it comes to new technologyCan’t stay away from the shiny new stuffPlease don’t drop any new coins during the presentationWho am I?
Overview of ASP.NET MVCOverview of Entity FrameworkThings that are coolThings to watch out forHow to do itAgenda
Demo
ModelsViewsControllersNo PostbacksVery limited use of existing server controlsClean HTML makes CSS and JavaScript easierWhat all the cool kids are using these days.ASP.NET MVC
First version (V 1) came with .NET 3.5 SP1 August 2008Not widely thought of by the communitySecond version (V4) released with .NET 4Maps POCO objects to Database objectsA collection of things instead of a dataset of rowsā€œthingsā€ are the EntitiesEntity Framework
Why?Adds a layer of abstraction between Database and CodeDBA can structure DB how they wantDeveloper can map to the DB how they wantRename Entities for more comfortable use.EF handles the mappingEntity Framework
Entity Data Model – EDMDeals with the Entities and the Relationships they useEntitiesInstance of EntityTypeRepresent individual instances of the objectsCustomer, books, shoesFully typedRelationshipsV1 was difficult to work with relationshipsNeeded special tricks to load related dataEntity FrameworkDefinitions
Adding an EDM to your projectDemo
A design pattern to defer initialization until needed.
EF 4 fixes a lot of problems with this
Supports Lazy Loading
OFF by default
ObjectContext setting, not application settingcontext.ContextOptions.DeferredLoadingEnabled=true;List<Thing> things = context.Things.ToList();foreach(var thing in things){varthingItems = thing.ThingItems}Entity FrameworkLazy Loading
Use if you will be needing every related entityList<Thing> things = context.Things.Include(ā€œThingItemsā€);foreach(var thing in things){varthingItems = thing.ThingItems}Entity FrameworkEager Loading
The context is the instance of the entityPassing an entity around to tiers breaks the contextV4 handles this issue with ā€œself-trackingā€ entitiesMake sure the context is always the sameEntity FrameworkContexts
Entity FrameworkContextspublic class ModelHelper    {        private static CourseEntities _db;        public static CourseEntitiesCourseEntities        {            get            {                if(_db == null)                    _db = new CourseEntities();                return _db;            }            set { _db = value; }        }    } private readonlyCourseEntities _db = new CourseEntities();
Entity FrameworkContextsprivate Student AddStudent(Student student, Course course){student.Courses.Add(course);_db.SaveChanges();}Didn’t work because course was in a different contextprivate Student AddStudent(Student student, Course course){varnewStudent = GetStudent(student.Id);varnewCourse = GetCourse(course.Id);newStudent.Courses.Add(newCourse);	_db.SaveChanges();}
Very similar to LINQ to SQLMajor differenceLINQ to SQL - .SingleOrDefault()LINQ to Entities - .FirstOrDefault()Selectingpublic Course GetCourse(int id){var course = (from c in _db.Courses                 where c.Id.Equals(id)                 select c).FirstOrDefault();   return course;}Entity FrameworkLINQ to Entities
Deletingpublic void DeleteCourse(Course course){	_db.DeleteObject(course);  _db.SaveChanges();}Adding (Inserting)public void AddCourse(Course course){   _db.AddToCourses(course); //this will be a list of AddToX   _db.SaveChanges();}Entity FrameworkLINQ to Entities

More Related Content

PPTX
Entity framework code first
Confiz
Ā 
PPTX
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
Ā 
PPT
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Pallepati Vasavi
Ā 
PPTX
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
Ā 
PPTX
introdution to SQL and SQL functions
farwa waqar
Ā 
PPTX
Getting started with entity framework
Lushanthan Sivaneasharajah
Ā 
PPTX
Database development life cycle unit 2 part 1
Ram Paliwal
Ā 
PPTX
Sql - Structured Query Language
Wan Hussain Wan Ishak
Ā 
Entity framework code first
Confiz
Ā 
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
Ā 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Pallepati Vasavi
Ā 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
Ā 
introdution to SQL and SQL functions
farwa waqar
Ā 
Getting started with entity framework
Lushanthan Sivaneasharajah
Ā 
Database development life cycle unit 2 part 1
Ram Paliwal
Ā 
Sql - Structured Query Language
Wan Hussain Wan Ishak
Ā 

What's hot (20)

PPTX
SQL Basics
Hammad Rasheed
Ā 
PPTX
Ado.net
Om Prakash
Ā 
PDF
Presto - Analytical Database. Overview and use cases.
Wojciech Biela
Ā 
PPTX
Laravel Tutorial PPT
Piyush Aggarwal
Ā 
PDF
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
Ā 
PPT
ADO .Net
DrSonali Vyas
Ā 
PPT
C# Exceptions Handling
sharqiyem
Ā 
PPT
IS740 Chapter 05
iDocs
Ā 
PDF
Introduction to Sightly
Ankit Gubrani
Ā 
PPTX
Namespaces in C#
yogita kachve
Ā 
PDF
CSS Unit I - Basics of JavaScript Programming
RahulTamkhane
Ā 
PPT
Asp.net.
Naveen Sihag
Ā 
PDF
Java ArrayList Tutorial | Edureka
Edureka!
Ā 
PPTX
Complete Lecture on Css presentation
Salman Memon
Ā 
PDF
SQL - RDBMS Concepts
WebStackAcademy
Ā 
PDF
Laravel tutorial
Broker IG
Ā 
PDF
Datastructure
Griffinder VinHai
Ā 
PPTX
Dynamic components using SPA concepts in AEM
Bojana Popovska
Ā 
PPT
Working with Databases and MySQL
Nicole Ryan
Ā 
SQL Basics
Hammad Rasheed
Ā 
Ado.net
Om Prakash
Ā 
Presto - Analytical Database. Overview and use cases.
Wojciech Biela
Ā 
Laravel Tutorial PPT
Piyush Aggarwal
Ā 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
Ā 
ADO .Net
DrSonali Vyas
Ā 
C# Exceptions Handling
sharqiyem
Ā 
IS740 Chapter 05
iDocs
Ā 
Introduction to Sightly
Ankit Gubrani
Ā 
Namespaces in C#
yogita kachve
Ā 
CSS Unit I - Basics of JavaScript Programming
RahulTamkhane
Ā 
Asp.net.
Naveen Sihag
Ā 
Java ArrayList Tutorial | Edureka
Edureka!
Ā 
Complete Lecture on Css presentation
Salman Memon
Ā 
SQL - RDBMS Concepts
WebStackAcademy
Ā 
Laravel tutorial
Broker IG
Ā 
Datastructure
Griffinder VinHai
Ā 
Dynamic components using SPA concepts in AEM
Bojana Popovska
Ā 
Working with Databases and MySQL
Nicole Ryan
Ā 
Ad

Viewers also liked (17)

PPT
Parallel Extentions to the .NET Framework
ukdpe
Ā 
PPT
ASP.NET MVC: new era?
Alexander Konduforov
Ā 
DOCX
LearningMVCWithLINQToSQL
Akhil Mittal
Ā 
PPTX
Real-time ASP.NET with SignalR
Alexander Konduforov
Ā 
PPTX
ASP.NET MVC and Entity Framework 4
James Johnson
Ā 
PPT
Ling to SQL and Entity Framework performance analysis
Alexander Konduforov
Ā 
PPT
Building a MVC eCommerce Site in Under 5 Minutes
Gaines Kergosien
Ā 
KEY
Introducing LINQ
LearnNowOnline
Ā 
PPTX
.NET,ASP .NET, Angular Js,LinQ
Avijit Shaw
Ā 
PPTX
Entity framework and how to use it
nspyre_net
Ā 
PPTX
Dotnet Frameworks Version History
voltaincx
Ā 
PPT
Introduccion a LINQ
Tonymx
Ā 
PPTX
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
Ā 
PPTX
Introducing Entity Framework 4.0
Bishoy Demian
Ā 
PPTX
ASP.NET MVC Performance
rudib
Ā 
PPSX
Introduction to .net framework
Arun Prasad
Ā 
Parallel Extentions to the .NET Framework
ukdpe
Ā 
ASP.NET MVC: new era?
Alexander Konduforov
Ā 
LearningMVCWithLINQToSQL
Akhil Mittal
Ā 
Real-time ASP.NET with SignalR
Alexander Konduforov
Ā 
ASP.NET MVC and Entity Framework 4
James Johnson
Ā 
Ling to SQL and Entity Framework performance analysis
Alexander Konduforov
Ā 
Building a MVC eCommerce Site in Under 5 Minutes
Gaines Kergosien
Ā 
Introducing LINQ
LearnNowOnline
Ā 
.NET,ASP .NET, Angular Js,LinQ
Avijit Shaw
Ā 
Entity framework and how to use it
nspyre_net
Ā 
Dotnet Frameworks Version History
voltaincx
Ā 
Introduccion a LINQ
Tonymx
Ā 
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
Ā 
Introducing Entity Framework 4.0
Bishoy Demian
Ā 
ASP.NET MVC Performance
rudib
Ā 
Introduction to .net framework
Arun Prasad
Ā 
Ad

Similar to MVC and Entity Framework (20)

PPTX
MVC and Entity Framework 4
James Johnson
Ā 
PPTX
MVC and Entity Framework 4
James Johnson
Ā 
PPTX
Entity Framework 4
Stefano Paluello
Ā 
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
Ā 
PPTX
Real World MVC
James Johnson
Ā 
PPT
Ef Poco And Unit Testing
James Phillips
Ā 
PPTX
La sql
James Johnson
Ā 
PPTX
Entity Framework Database and Code First
James Johnson
Ā 
PPTX
Poco Es Mucho: WCF, EF, and Class Design
James Phillips
Ā 
PDF
Intro to Core Data
Make School
Ā 
PPT
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
Ā 
PDF
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
Ā 
PPTX
Adding a modern twist to legacy web applications
Jeff Durta
Ā 
PPTX
Entity Framework v2 Best Practices
Andri Yadi
Ā 
PPT
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
Ā 
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
Ā 
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
Ā 
PDF
Intake 37 ef2
Mahmoud Ouf
Ā 
PPTX
Entity Framework Today (May 2012)
Julie Lerman
Ā 
PPT
What's New for Data?
ukdpe
Ā 
MVC and Entity Framework 4
James Johnson
Ā 
MVC and Entity Framework 4
James Johnson
Ā 
Entity Framework 4
Stefano Paluello
Ā 
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
Ā 
Real World MVC
James Johnson
Ā 
Ef Poco And Unit Testing
James Phillips
Ā 
La sql
James Johnson
Ā 
Entity Framework Database and Code First
James Johnson
Ā 
Poco Es Mucho: WCF, EF, and Class Design
James Phillips
Ā 
Intro to Core Data
Make School
Ā 
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
Ā 
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
Ā 
Adding a modern twist to legacy web applications
Jeff Durta
Ā 
Entity Framework v2 Best Practices
Andri Yadi
Ā 
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
Ā 
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
Ā 
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
Ā 
Intake 37 ef2
Mahmoud Ouf
Ā 
Entity Framework Today (May 2012)
Julie Lerman
Ā 
What's New for Data?
ukdpe
Ā 

Recently uploaded (20)

PDF
Software Development Methodologies in 2025
KodekX
Ā 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
Ā 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
Ā 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
Ā 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
Ā 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
Ā 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
Ā 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
Ā 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
Ā 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
Ā 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
Ā 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
Ā 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
Ā 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
Ā 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
Ā 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
Ā 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
Ā 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
Ā 
Software Development Methodologies in 2025
KodekX
Ā 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
Ā 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
Ā 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
Ā 
DevOps & Developer Experience Summer BBQ
AUGNYC
Ā 
REPORT: Heating appliances market in Poland 2024
SPIUG
Ā 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
Ā 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
Ā 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
Ā 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
Ā 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
Ā 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
Ā 
L2 Rules of Netiquette in Empowerment technology
Archibal2
Ā 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
Ā 
Coupa-Overview _Assumptions presentation
annapureddyn
Ā 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
Ā 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
Ā 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
Ā 

MVC and Entity Framework

  • 1. ASP.NET MVC and Entity FrameworkUtah Code CampSaturday, September 25, 2010James JohnsonTechnical Evangelist
  • 2. Technical Evangelist with ComponentOneFounder and President of the Inland Empire .NET User’s GroupMicrosoft MVPBut I don’t consider myself an expert. I just love to playADHD/ADD/OCD when it comes to new technologyCan’t stay away from the shiny new stuffPlease don’t drop any new coins during the presentationWho am I?
  • 3. Overview of ASP.NET MVCOverview of Entity FrameworkThings that are coolThings to watch out forHow to do itAgenda
  • 5. ModelsViewsControllersNo PostbacksVery limited use of existing server controlsClean HTML makes CSS and JavaScript easierWhat all the cool kids are using these days.ASP.NET MVC
  • 6. First version (V 1) came with .NET 3.5 SP1 August 2008Not widely thought of by the communitySecond version (V4) released with .NET 4Maps POCO objects to Database objectsA collection of things instead of a dataset of rowsā€œthingsā€ are the EntitiesEntity Framework
  • 7. Why?Adds a layer of abstraction between Database and CodeDBA can structure DB how they wantDeveloper can map to the DB how they wantRename Entities for more comfortable use.EF handles the mappingEntity Framework
  • 8. Entity Data Model – EDMDeals with the Entities and the Relationships they useEntitiesInstance of EntityTypeRepresent individual instances of the objectsCustomer, books, shoesFully typedRelationshipsV1 was difficult to work with relationshipsNeeded special tricks to load related dataEntity FrameworkDefinitions
  • 9. Adding an EDM to your projectDemo
  • 10. A design pattern to defer initialization until needed.
  • 11. EF 4 fixes a lot of problems with this
  • 14. ObjectContext setting, not application settingcontext.ContextOptions.DeferredLoadingEnabled=true;List<Thing> things = context.Things.ToList();foreach(var thing in things){varthingItems = thing.ThingItems}Entity FrameworkLazy Loading
  • 15. Use if you will be needing every related entityList<Thing> things = context.Things.Include(ā€œThingItemsā€);foreach(var thing in things){varthingItems = thing.ThingItems}Entity FrameworkEager Loading
  • 16. The context is the instance of the entityPassing an entity around to tiers breaks the contextV4 handles this issue with ā€œself-trackingā€ entitiesMake sure the context is always the sameEntity FrameworkContexts
  • 17. Entity FrameworkContextspublic class ModelHelper { private static CourseEntities _db; public static CourseEntitiesCourseEntities { get { if(_db == null) _db = new CourseEntities(); return _db; } set { _db = value; } } } private readonlyCourseEntities _db = new CourseEntities();
  • 18. Entity FrameworkContextsprivate Student AddStudent(Student student, Course course){student.Courses.Add(course);_db.SaveChanges();}Didn’t work because course was in a different contextprivate Student AddStudent(Student student, Course course){varnewStudent = GetStudent(student.Id);varnewCourse = GetCourse(course.Id);newStudent.Courses.Add(newCourse); _db.SaveChanges();}
  • 19. Very similar to LINQ to SQLMajor differenceLINQ to SQL - .SingleOrDefault()LINQ to Entities - .FirstOrDefault()Selectingpublic Course GetCourse(int id){var course = (from c in _db.Courses where c.Id.Equals(id) select c).FirstOrDefault(); return course;}Entity FrameworkLINQ to Entities
  • 20. Deletingpublic void DeleteCourse(Course course){ _db.DeleteObject(course); _db.SaveChanges();}Adding (Inserting)public void AddCourse(Course course){ _db.AddToCourses(course); //this will be a list of AddToX _db.SaveChanges();}Entity FrameworkLINQ to Entities
  • 21. Editing (Updating)public void EditCourse(Course course){ _db.Courses.Attach(new Course { Id = course.Id }); _db.Courses.ApplyCurrentValues(course); _db.SaveChanges();}ā€œcourseā€ has been edited somewhere else – MVC Controller, so a ā€œstand-inā€ is createdEntity FrameworkLINQ to Entities
  • 23. Tweet ā€œ@componentone <3’s Utah Code Campā€ for a second chance to win
  • 24. James [email protected], @latringoInland Empire .NET User’s Groupwww.iedotnetug.org2nd Tuesday’s of each month in RiversideThank you