SlideShare une entreprise Scribd logo
1  sur  23
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

Contenu connexe

Tendances

Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
WO Community
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
WO Community
 
Intro to java programming
Intro to java programmingIntro to java programming
Intro to java programming
Leah Stephens
 

Tendances (20)

Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScriptReact Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
 
Web without framework
Web without frameworkWeb without framework
Web without framework
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Intro to java programming
Intro to java programmingIntro to java programming
Intro to java programming
 
Dapper: the microORM that will change your life
Dapper: the microORM that will change your lifeDapper: the microORM that will change your life
Dapper: the microORM that will change your life
 
Building intranet applications with ASP.NET AJAX and jQuery
Building intranet applications with ASP.NET AJAX and jQueryBuilding intranet applications with ASP.NET AJAX and jQuery
Building intranet applications with ASP.NET AJAX and jQuery
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
 
Uklug2012 yellow and blue stream
Uklug2012 yellow and blue streamUklug2012 yellow and blue stream
Uklug2012 yellow and blue stream
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with Javascript
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino API
 
Quick start with AngularJS
Quick start with AngularJSQuick start with AngularJS
Quick start with AngularJS
 
iOS Beginners Lesson 3
iOS Beginners Lesson 3iOS Beginners Lesson 3
iOS Beginners Lesson 3
 
React && React Native workshop
React && React Native workshopReact && React Native workshop
React && React Native workshop
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
 

Similaire à ASP.NET MVC and Entity Framework 4

Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
Richie Rump
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
WO Community
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure Functions
Sébastien Levert
 

Similaire à ASP.NET MVC and Entity Framework 4 (20)

MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Lerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In AspnetLerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In Aspnet
 
70487.pdf
70487.pdf70487.pdf
70487.pdf
 
Learn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstLearn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database First
 
04 integrate entityframework
04 integrate entityframework04 integrate entityframework
04 integrate entityframework
 
Entity Framework 4 In Microsoft Visual Studio 2010
Entity Framework 4 In Microsoft Visual Studio 2010Entity Framework 4 In Microsoft Visual Studio 2010
Entity Framework 4 In Microsoft Visual Studio 2010
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
JS Essence
JS EssenceJS Essence
JS Essence
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure Functions
 
Web Development with Delphi and React - ITDevCon 2016
Web Development with Delphi and React - ITDevCon 2016Web Development with Delphi and React - ITDevCon 2016
Web Development with Delphi and React - ITDevCon 2016
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

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
  • 23. 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