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

What's hot (20)

PPTX
Abstraction java
MahinImran
 
PPTX
Recommendation Systems
Robin Reni
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPT
C# basics
Dinesh kumar
 
PPTX
Entity framework code first
Confiz
 
PDF
Spring annotation
Rajiv Srivastava
 
PDF
Selenium IDE LOCATORS
Mindfire Solutions
 
PDF
Java Servlets.pdf
Arumugam90
 
PDF
Test Automation Using Python | Edureka
Edureka!
 
PDF
Test Automation Tool comparison – HP UFT/QTP vs. Selenium
Aspire Systems
 
PPTX
Selenium Locators
Satyam Pandey
 
PDF
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
DOCX
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 
PPTX
Decorator Pattern
Dimuthu Anuraj
 
PPTX
Python selenium
Ducat
 
PDF
Recommender Systems
T212
 
PDF
Extensible Data Modeling
Karwin Software Solutions LLC
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PDF
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
PPTX
Spring Web MVC
zeeshanhanif
 
Abstraction java
MahinImran
 
Recommendation Systems
Robin Reni
 
Collections in Java Notes
Shalabh Chaudhary
 
C# basics
Dinesh kumar
 
Entity framework code first
Confiz
 
Spring annotation
Rajiv Srivastava
 
Selenium IDE LOCATORS
Mindfire Solutions
 
Java Servlets.pdf
Arumugam90
 
Test Automation Using Python | Edureka
Edureka!
 
Test Automation Tool comparison – HP UFT/QTP vs. Selenium
Aspire Systems
 
Selenium Locators
Satyam Pandey
 
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 
Decorator Pattern
Dimuthu Anuraj
 
Python selenium
Ducat
 
Recommender Systems
T212
 
Extensible Data Modeling
Karwin Software Solutions LLC
 
Introduction to Spring Framework
Serhat Can
 
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
Spring Web MVC
zeeshanhanif
 

Viewers also liked (18)

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
Getting started with entity framework
Lushanthan Sivaneasharajah
 
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
 
Getting started with entity framework
Lushanthan Sivaneasharajah
 
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
 
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
 
Ad

Recently uploaded (20)

PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Digital Circuits, important subject in CS
contactparinay1
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 

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