SlideShare a Scribd company logo
ASP.NET MVC and Entity Framework
Desert Code Camp
Saturday, November 13, 2010
James Johnson
Technical Evangelist
• Technical Evangelist with ComponentOne
• Founder and President of the Inland Empire .NET User’s
Group
• Microsoft MVP
• But I don’t consider myself an expert. I just love to play
• ADHD/ADD/OCD when it comes to new technology
• Can’t stay away from the shiny new stuff
• Please don’t drop any new coins during the presentation
Who am I?
• Overview of ASP.NET MVC
• Basic MVC Application
• Models, Views, Controls, Helpers
• Overview of Entity Framework
• Things that are cool
• Things to watch out for
• How to do it
Agenda
Demo
• Models
• Views
• Controllers
• No Post backs
• Very limited use of existing server controls
• Clean HTML makes CSS and JavaScript easier
• What all the cool kids are using these days.
ASP.NET MVC
• First version (V 1) came with .NET 3.5 SP1
• August 2008
• Not widely thought of by the community
• Second version (V4) released with .NET 4
• Maps POCO objects to Database objects
• A collection of things instead of a dataset of rows
• “things” are the Entities
Entity Framework
• Why?
• Adds a layer of abstraction between Database and Code
• DBA can structure DB how they want
• Developer can map to the DB how they want
• Rename Entities for more comfortable use.
• EF handles the mapping
Entity Framework
• Entity Data Model – EDM
• Deals with the Entities and the Relationships they use
• Entities
• Instance of EntityType
• Represent individual instances of the objects
• Customer, books, shoes
• Fully typed
• Relationships
• V1 was difficult to work with relationships
• Needed special tricks to load related data
Entity Framework
Definitions
Adding an EDM to your project
Demo
• 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 setting
context.ContextOptions.DeferredLoadingEnabled=true;
List<Thing> things = context.Things.ToList();
foreach(var thing in things)
{
var thingItems = thing.ThingItems
}
Entity Framework
Lazy Loading
Use if you will be needing every related entity
List<Thing> things = context.Things.Include(“ThingItems”);
foreach(var thing in things)
{
var thingItems = thing.ThingItems
}
Entity Framework
Eager Loading
• The context is the instance of the entity
• Passing an entity around to tiers breaks the context
• V4 handles this issue with “self-tracking” entities
• Make sure the context is always the same
Entity Framework
Contexts
Entity Framework
Contexts
public class ModelHelper
{
private static CourseEntities _db;
public static CourseEntities CourseEntities
{
get
{
if(_db == null)
_db = new CourseEntities();
return _db;
}
set { _db = value; }
}
}
private readonly CourseEntities _db = new CourseEntities();
Entity Framework
Contexts
private Student AddStudent(Student student, Course course)
{
student.Courses.Add(course);
_db.SaveChanges();
}
Didn’t work because course was in a different context
private Student AddStudent(Student student, Course course)
{
var newStudent = GetStudent(student.Id);
var newCourse = GetCourse(course.Id);
newStudent.Courses.Add(newCourse);
_db.SaveChanges();
}
• Very similar to LINQ to SQL
• Major difference
• LINQ to SQL - .SingleOrDefault()
• LINQ to Entities - .FirstOrDefault()
Selecting
public Course GetCourse(int id)
{
var course = (from c in _db.Courses
where c.Id.Equals(id)
select c).FirstOrDefault();
return course;
}
Entity Framework
LINQ to Entities
Deleting
public 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 Framework
LINQ to Entities
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 created
Entity Framework
LINQ to Entities
• Repository pattern encapsulates code into a separate
class
• Allows for easy changes
• Can use it to switch database providers or new
technologies
• Stephen Walther – ASP.NET MVC Framework, Sams
• stephenwalther.com
• “Download the code” link
Repositories
Repositories
• Add the two projects to your solution
• Add references to your project
using GenericRepository
public class MyController
{
private readonly IGenericRepository _repo;
private readonly CourseEntities _db;
public MyController()
{
_repo = new EFGenericRepository.EFGenericRepository(_db);
}
}
Repositories
// get
_repo.Get<Course>(id);
// edit
_repo.Edit(course);
// create
_repo.Create(course);
// delete
_repo.Delete(course);
// list
var list = _repo.List<Course>().Where(x => x.CourseName.Contains());
Repositories
Questions?
James Johnson
jamesj@componentone.com
http://c1.ms/latringo
www.speakerrate.com/latringo
http://bit.ly/latringo_dcc
Twitter, @latringo
Inland Empire .NET User’s Group
www.iedotnetug.org
2nd Tuesday’s of each month in Riverside, CA
Thank you

More Related Content

What's hot (20)

PDF
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
Kobkrit Viriyayudhakorn
 
PDF
Web without framework
Nicolas Jorand
 
PDF
Unit Testing with WOUnit
WO Community
 
PDF
D2W Stateful Controllers
WO Community
 
PPTX
Intro to java programming
Leah Stephens
 
PPTX
Dapper: the microORM that will change your life
Davide Mauri
 
PPT
Building intranet applications with ASP.NET AJAX and jQuery
Alek Davis
 
PDF
Life outside WO
WO Community
 
PPT
Uklug2012 yellow and blue stream
Frank van der Linden
 
PPTX
Getting Started with Javascript
Akshay Mathur
 
PPTX
Getting Started with jQuery
Akshay Mathur
 
PDF
[2015/2016] Local data storage for web-based mobile apps
Ivano Malavolta
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PPTX
Utilizing the OpenNTF Domino API
Oliver Busse
 
PDF
Quick start with AngularJS
Iuliia Baranova
 
PPTX
iOS Beginners Lesson 3
Calvin Cheng
 
PDF
React && React Native workshop
Stacy Goh
 
PPTX
Object Oriented Programing in JavaScript
Akshay Mathur
 
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
Kobkrit Viriyayudhakorn
 
Web without framework
Nicolas Jorand
 
Unit Testing with WOUnit
WO Community
 
D2W Stateful Controllers
WO Community
 
Intro to java programming
Leah Stephens
 
Dapper: the microORM that will change your life
Davide Mauri
 
Building intranet applications with ASP.NET AJAX and jQuery
Alek Davis
 
Life outside WO
WO Community
 
Uklug2012 yellow and blue stream
Frank van der Linden
 
Getting Started with Javascript
Akshay Mathur
 
Getting Started with jQuery
Akshay Mathur
 
[2015/2016] Local data storage for web-based mobile apps
Ivano Malavolta
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Utilizing the OpenNTF Domino API
Oliver Busse
 
Quick start with AngularJS
Iuliia Baranova
 
iOS Beginners Lesson 3
Calvin Cheng
 
React && React Native workshop
Stacy Goh
 
Object Oriented Programing in JavaScript
Akshay Mathur
 

Similar to ASP.NET MVC and Entity Framework 4 (20)

PPTX
MVC and Entity Framework
James Johnson
 
PPTX
MVC and Entity Framework 4
James Johnson
 
PPTX
Real World MVC
James Johnson
 
PPTX
Lerman Adx303 Entity Framework 4 In Aspnet
Julie Lerman
 
PDF
70487.pdf
Karen Benoit
 
PDF
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
PPTX
04 integrate entityframework
Erhwen Kuo
 
PPT
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
 
PPTX
Entity Framework Today (May 2012)
Julie Lerman
 
PPTX
Entity Framework 4
Stefano Paluello
 
PPTX
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
PPTX
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
PDF
Apache Cayenne for WO Devs
WO Community
 
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
 
PDF
Stencil the time for vanilla web components has arrived
Gil Fink
 
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
 
PPTX
JS Essence
Uladzimir Piatryka
 
PPTX
SharePoint Framework, Angular and Azure Functions
Sébastien Levert
 
PDF
Web Development with Delphi and React - ITDevCon 2016
Marco Breveglieri
 
PDF
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
WO Community
 
MVC and Entity Framework
James Johnson
 
MVC and Entity Framework 4
James Johnson
 
Real World MVC
James Johnson
 
Lerman Adx303 Entity Framework 4 In Aspnet
Julie Lerman
 
70487.pdf
Karen Benoit
 
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
04 integrate entityframework
Erhwen Kuo
 
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
 
Entity Framework Today (May 2012)
Julie Lerman
 
Entity Framework 4
Stefano Paluello
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
Apache Cayenne for WO Devs
WO Community
 
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
 
Stencil the time for vanilla web components has arrived
Gil Fink
 
Building nTier Applications with Entity Framework Services (Part 1)
David McCarter
 
JS Essence
Uladzimir Piatryka
 
SharePoint Framework, Angular and Azure Functions
Sébastien Levert
 
Web Development with Delphi and React - ITDevCon 2016
Marco Breveglieri
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
WO Community
 
Ad

Recently uploaded (20)

PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Ad

ASP.NET MVC and Entity Framework 4

  • 1. ASP.NET MVC and Entity Framework Desert Code Camp Saturday, November 13, 2010 James Johnson Technical Evangelist
  • 2. • Technical Evangelist with ComponentOne • Founder and President of the Inland Empire .NET User’s Group • Microsoft MVP • But I don’t consider myself an expert. I just love to play • ADHD/ADD/OCD when it comes to new technology • Can’t stay away from the shiny new stuff • Please don’t drop any new coins during the presentation Who am I?
  • 3. • Overview of ASP.NET MVC • Basic MVC Application • Models, Views, Controls, Helpers • Overview of Entity Framework • Things that are cool • Things to watch out for • How to do it Agenda
  • 5. • Models • Views • Controllers • No Post backs • Very limited use of existing server controls • Clean HTML makes CSS and JavaScript easier • What all the cool kids are using these days. ASP.NET MVC
  • 6. • First version (V 1) came with .NET 3.5 SP1 • August 2008 • Not widely thought of by the community • Second version (V4) released with .NET 4 • Maps POCO objects to Database objects • A collection of things instead of a dataset of rows • “things” are the Entities Entity Framework
  • 7. • Why? • Adds a layer of abstraction between Database and Code • DBA can structure DB how they want • Developer can map to the DB how they want • Rename Entities for more comfortable use. • EF handles the mapping Entity Framework
  • 8. • Entity Data Model – EDM • Deals with the Entities and the Relationships they use • Entities • Instance of EntityType • Represent individual instances of the objects • Customer, books, shoes • Fully typed • Relationships • V1 was difficult to work with relationships • Needed special tricks to load related data Entity Framework Definitions
  • 9. Adding an EDM to your project Demo
  • 10. • 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 setting context.ContextOptions.DeferredLoadingEnabled=true; List<Thing> things = context.Things.ToList(); foreach(var thing in things) { var thingItems = thing.ThingItems } Entity Framework Lazy Loading
  • 11. Use if you will be needing every related entity List<Thing> things = context.Things.Include(“ThingItems”); foreach(var thing in things) { var thingItems = thing.ThingItems } Entity Framework Eager Loading
  • 12. • The context is the instance of the entity • Passing an entity around to tiers breaks the context • V4 handles this issue with “self-tracking” entities • Make sure the context is always the same Entity Framework Contexts
  • 13. Entity Framework Contexts public class ModelHelper { private static CourseEntities _db; public static CourseEntities CourseEntities { get { if(_db == null) _db = new CourseEntities(); return _db; } set { _db = value; } } } private readonly CourseEntities _db = new CourseEntities();
  • 14. Entity Framework Contexts private Student AddStudent(Student student, Course course) { student.Courses.Add(course); _db.SaveChanges(); } Didn’t work because course was in a different context private Student AddStudent(Student student, Course course) { var newStudent = GetStudent(student.Id); var newCourse = GetCourse(course.Id); newStudent.Courses.Add(newCourse); _db.SaveChanges(); }
  • 15. • Very similar to LINQ to SQL • Major difference • LINQ to SQL - .SingleOrDefault() • LINQ to Entities - .FirstOrDefault() Selecting public Course GetCourse(int id) { var course = (from c in _db.Courses where c.Id.Equals(id) select c).FirstOrDefault(); return course; } Entity Framework LINQ to Entities
  • 16. Deleting public 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 Framework LINQ to Entities
  • 17. 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 created Entity Framework LINQ to Entities
  • 18. • Repository pattern encapsulates code into a separate class • Allows for easy changes • Can use it to switch database providers or new technologies • Stephen Walther – ASP.NET MVC Framework, Sams • stephenwalther.com • “Download the code” link Repositories
  • 19. Repositories • Add the two projects to your solution • Add references to your project
  • 20. using GenericRepository public class MyController { private readonly IGenericRepository _repo; private readonly CourseEntities _db; public MyController() { _repo = new EFGenericRepository.EFGenericRepository(_db); } } Repositories
  • 21. // get _repo.Get<Course>(id); // edit _repo.Edit(course); // create _repo.Create(course); // delete _repo.Delete(course); // list var list = _repo.List<Course>().Where(x => x.CourseName.Contains()); Repositories