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
 
DOCX
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
PPTX
Entity Framework 4
Stefano Paluello
 
PPT
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
 
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
PPTX
05 entity framework
glubox
 
PPTX
Entity Framework Today (May 2012)
Julie Lerman
 
DOCX
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
PDF
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
PPTX
Lerman Adx303 Entity Framework 4 In Aspnet
Julie Lerman
 
PDF
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
PPTX
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
PDF
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
PPTX
Usando el entity framework
Juan Camilo Sacanamboy
 
PPTX
Entity Framework
vrluckyin
 
PPTX
Entity framework
icubesystem
 
PPTX
Real World MVC
James Johnson
 
DOCX
Getting Started with Entity Framework in .NET
StudySection
 
PDF
Entity frame work by Salman Mushtaq -1-
Salman Mushtaq
 
MVC and Entity Framework 4
James Johnson
 
MVC and Entity Framework 4
James Johnson
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Entity Framework 4
Stefano Paluello
 
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
05 entity framework
glubox
 
Entity Framework Today (May 2012)
Julie Lerman
 
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
Lerman Adx303 Entity Framework 4 In Aspnet
Julie Lerman
 
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
Usando el entity framework
Juan Camilo Sacanamboy
 
Entity Framework
vrluckyin
 
Entity framework
icubesystem
 
Real World MVC
James Johnson
 
Getting Started with Entity Framework in .NET
StudySection
 
Entity frame work by Salman Mushtaq -1-
Salman Mushtaq
 
Ad

Recently uploaded (20)

PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Digital Circuits, important subject in CS
contactparinay1
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 

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