SlideShare a Scribd company logo
ASP.NET MVC and Entity FrameworkSan Diego .NET User GroupTuesday, March 23, 2010James Johnson
Founder and President of the Inland Empire .NET User’s GroupIndependent ConsultantMicrosoft 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 shiny coins during the presentationWho am I?
An effort to help support local user groups by providing speakersTelerik speakers bureau
Overview of ASP.NET MVCOverview of Entity FrameworkThings that are coolThings to watch out forHow to do itAgenda
Demo
V 2.0 RTM’d March 11, 2010ModelsViewsControllersNo PostbacksVery limited use of existing server controlsClean HTML makes CSS and JavaScript easierWhat all the cool kids are using these days.ASP.NET MVC
Hey! There’s a big honking server control there!Using the TelerikRadEditor in this projectVery easy to setup if you follow these rulesNeeds to be in a “form” tag, not Html.BeginForm()Handlers need to be changed from .aspx to .axdDialogHandlerUrl, SpellCheckChettingsUse a custom tools fileASP.NET MVCTelerikRadEditor
Setting<% RadEditor1.Content = Model.Description %>GettingNeed to pass in the request and name of editorASP.NET MVCTelerikRadEditor Set and Get Contentvarcontent = _radControlHelper.GetEditorContent(Request, “RadEditor1");public string GetEditorContent(HttpRequestBase request, string editorId){varrawContent = (from postedValue in request.Form.Keys.OfType<string>()                              where postedValue.EndsWith(editorId)                              select request.Form[postedValue]).FirstOrDefault();return Telerik.Web.UI.Editor.ContentEncoder.Decode(rawContent);}
First version (V 1) came with .NET 3.5 SP1 August 2008Not widely thought of by the communitySecond version (V4) is set to be 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 thisSupports Lazy LoadingOFF by defaultObjectContext 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 will handle 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
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
Questions?
James Johnsonjames@iedotnetug.orgwww.duringlunch.comTwitter, @latringoInland Empire .NET User’s Groupwww.iedotnetug.org2nd Tuesday’s of each month in RiversideThank you
Ad

Recommended

AD507 –Leveraging the Power of Object
AD507 –Leveraging the Power of Object
dominion
 
Storage in the Windows Azure Platform - ericnel
Storage in the Windows Azure Platform - ericnel
ukdpe
 
Dot Net Accenture
Dot Net Accenture
Sri K
 
An Overview of Entity Framework
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
jpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
hibernate with JPA
hibernate with JPA
Mohammad Faizan
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
Alexander Pashynskiy
 
Object identification and its management
Object identification and its management
Vinay Kumar Pulabaigari
 
React JS Interview Question & Answer
React JS Interview Question & Answer
Mildain Solutions
 
Entity Framework Database and Code First
Entity Framework Database and Code First
James Johnson
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
ejlp12
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
JPA and Hibernate
JPA and Hibernate
elliando dias
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Marco Tusa
 
Spring Test DBUnit
Spring Test DBUnit
Jaran Flaath
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
Introduction to jQuery
Introduction to jQuery
Collaboration Technologies
 
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
Hibernate in Nutshell
Hibernate in Nutshell
Onkar Deshpande
 
ObjectCreatorUserGuide
ObjectCreatorUserGuide
Roger Robins
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
Dropping content isn't a drag!
Dropping content isn't a drag!
XMetaL
 
JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Buzzmedia Octagon Keynote
Buzzmedia Octagon Keynote
Chris George
 
Прикладной коннективизм
Прикладной коннективизм
Ivan Travkin
 

More Related Content

What's hot (20)

Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
Alexander Pashynskiy
 
Object identification and its management
Object identification and its management
Vinay Kumar Pulabaigari
 
React JS Interview Question & Answer
React JS Interview Question & Answer
Mildain Solutions
 
Entity Framework Database and Code First
Entity Framework Database and Code First
James Johnson
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
ejlp12
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
JPA and Hibernate
JPA and Hibernate
elliando dias
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Marco Tusa
 
Spring Test DBUnit
Spring Test DBUnit
Jaran Flaath
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
Introduction to jQuery
Introduction to jQuery
Collaboration Technologies
 
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
Hibernate in Nutshell
Hibernate in Nutshell
Onkar Deshpande
 
ObjectCreatorUserGuide
ObjectCreatorUserGuide
Roger Robins
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
Dropping content isn't a drag!
Dropping content isn't a drag!
XMetaL
 
JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
Alexander Pashynskiy
 
Object identification and its management
Object identification and its management
Vinay Kumar Pulabaigari
 
React JS Interview Question & Answer
React JS Interview Question & Answer
Mildain Solutions
 
Entity Framework Database and Code First
Entity Framework Database and Code First
James Johnson
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
ejlp12
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Bill Buchan
 
Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Marco Tusa
 
Spring Test DBUnit
Spring Test DBUnit
Jaran Flaath
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
ObjectCreatorUserGuide
ObjectCreatorUserGuide
Roger Robins
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
Fad Zulkifli
 
Dropping content isn't a drag!
Dropping content isn't a drag!
XMetaL
 
JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 

Viewers also liked (20)

Buzzmedia Octagon Keynote
Buzzmedia Octagon Keynote
Chris George
 
Прикладной коннективизм
Прикладной коннективизм
Ivan Travkin
 
Skema Bm Kertas2 Set2
Skema Bm Kertas2 Set2
Kay Aniza
 
Marketing Communications Spring 2008 Final Project
Marketing Communications Spring 2008 Final Project
lat886
 
Twitter for Journalists Utrecht june 11 2009
Twitter for Journalists Utrecht june 11 2009
Bart Brouwers
 
ADHD
ADHD
nolankr
 
Amphibians.d (1)
Amphibians.d (1)
Isabel Rojo
 
Amphibians
Amphibians
Isabel Rojo
 
Texas Instruments
Texas Instruments
DominikCzerwinski
 
Jeff Martin: Portfolio
Jeff Martin: Portfolio
Jeff Martin
 
A Historia
A Historia
curradbc
 
Informationliteracy
Informationliteracy
Ireubzaet
 
E Learners Presentation
E Learners Presentation
Jeanette Murphy
 
Plazacubiertaweb
Plazacubiertaweb
raqueleta
 
Soci2
Soci2
Teresa Olveira Nieto
 
Creatively Common (#BootCamp12)
Creatively Common (#BootCamp12)
Michael Fienen
 
The Moore-Spiegel Oscillator
The Moore-Spiegel Oscillator
Abhranil Das
 
A Search For Compassion
A Search For Compassion
Michelle
 
Buzzmedia Octagon Keynote
Buzzmedia Octagon Keynote
Chris George
 
Прикладной коннективизм
Прикладной коннективизм
Ivan Travkin
 
Skema Bm Kertas2 Set2
Skema Bm Kertas2 Set2
Kay Aniza
 
Marketing Communications Spring 2008 Final Project
Marketing Communications Spring 2008 Final Project
lat886
 
Twitter for Journalists Utrecht june 11 2009
Twitter for Journalists Utrecht june 11 2009
Bart Brouwers
 
Amphibians.d (1)
Amphibians.d (1)
Isabel Rojo
 
Jeff Martin: Portfolio
Jeff Martin: Portfolio
Jeff Martin
 
A Historia
A Historia
curradbc
 
Informationliteracy
Informationliteracy
Ireubzaet
 
Plazacubiertaweb
Plazacubiertaweb
raqueleta
 
Creatively Common (#BootCamp12)
Creatively Common (#BootCamp12)
Michael Fienen
 
The Moore-Spiegel Oscillator
The Moore-Spiegel Oscillator
Abhranil Das
 
A Search For Compassion
A Search For Compassion
Michelle
 
Ad

Similar to MVC and Entity Framework 4 (20)

MVC and Entity Framework
MVC and Entity Framework
James Johnson
 
MVC and Entity Framework 4
MVC and Entity Framework 4
James Johnson
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
James Johnson
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Entity framework and how to use it
Entity framework and how to use it
nspyre_net
 
05 entity framework
05 entity framework
glubox
 
Real World MVC
Real World MVC
James Johnson
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
Getting started with the entity framework 4.1 using asp.net mvc
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Lerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In Aspnet
Julie Lerman
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
Julie Lerman
 
Entity Framework 4
Entity Framework 4
Stefano Paluello
 
Entity Framework 4 In Microsoft Visual Studio 2010
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-
Salman Mushtaq
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
Entity frameworks101
Entity frameworks101
Rich Helton
 
Entity Framework 6 Recipes 2nd Edition Brian Driscoll
Entity Framework 6 Recipes 2nd Edition Brian Driscoll
raffygobahc9
 
.NET Core, ASP.NET Core Course, Session 13
.NET Core, ASP.NET Core Course, Session 13
Amin Mesbahi
 
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
pontyrincoe
 
MVC and Entity Framework
MVC and Entity Framework
James Johnson
 
MVC and Entity Framework 4
MVC and Entity Framework 4
James Johnson
 
ASP.NET MVC and Entity Framework 4
ASP.NET MVC and Entity Framework 4
James Johnson
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Entity framework and how to use it
Entity framework and how to use it
nspyre_net
 
05 entity framework
05 entity framework
glubox
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5
Ehtsham Khan
 
Getting started with the entity framework 4.1 using asp.net mvc
Getting started with the entity framework 4.1 using asp.net mvc
Steve Xu
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Lerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In Aspnet
Julie Lerman
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
Julie Lerman
 
Entity Framework 4 In Microsoft Visual Studio 2010
Entity Framework 4 In Microsoft Visual Studio 2010
Eric Nelson
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-
Salman Mushtaq
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
Entity frameworks101
Entity frameworks101
Rich Helton
 
Entity Framework 6 Recipes 2nd Edition Brian Driscoll
Entity Framework 6 Recipes 2nd Edition Brian Driscoll
raffygobahc9
 
.NET Core, ASP.NET Core Course, Session 13
.NET Core, ASP.NET Core Course, Session 13
Amin Mesbahi
 
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
pontyrincoe
 
Ad

Recently uploaded (20)

" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
The Growing Value and Application of FME & GenAI
The Growing Value and Application of FME & GenAI
Safe Software
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
The Growing Value and Application of FME & GenAI
The Growing Value and Application of FME & GenAI
Safe Software
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 

MVC and Entity Framework 4

  • 1. ASP.NET MVC and Entity FrameworkSan Diego .NET User GroupTuesday, March 23, 2010James Johnson
  • 2. Founder and President of the Inland Empire .NET User’s GroupIndependent ConsultantMicrosoft 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 shiny coins during the presentationWho am I?
  • 3. An effort to help support local user groups by providing speakersTelerik speakers bureau
  • 4. Overview of ASP.NET MVCOverview of Entity FrameworkThings that are coolThings to watch out forHow to do itAgenda
  • 6. V 2.0 RTM’d March 11, 2010ModelsViewsControllersNo PostbacksVery limited use of existing server controlsClean HTML makes CSS and JavaScript easierWhat all the cool kids are using these days.ASP.NET MVC
  • 7. Hey! There’s a big honking server control there!Using the TelerikRadEditor in this projectVery easy to setup if you follow these rulesNeeds to be in a “form” tag, not Html.BeginForm()Handlers need to be changed from .aspx to .axdDialogHandlerUrl, SpellCheckChettingsUse a custom tools fileASP.NET MVCTelerikRadEditor
  • 8. Setting<% RadEditor1.Content = Model.Description %>GettingNeed to pass in the request and name of editorASP.NET MVCTelerikRadEditor Set and Get Contentvarcontent = _radControlHelper.GetEditorContent(Request, “RadEditor1");public string GetEditorContent(HttpRequestBase request, string editorId){varrawContent = (from postedValue in request.Form.Keys.OfType<string>() where postedValue.EndsWith(editorId) select request.Form[postedValue]).FirstOrDefault();return Telerik.Web.UI.Editor.ContentEncoder.Decode(rawContent);}
  • 9. First version (V 1) came with .NET 3.5 SP1 August 2008Not widely thought of by the communitySecond version (V4) is set to be released with .NET 4Maps POCO objects to Database objectsA collection of things instead of a dataset of rows“things” are the EntitiesEntity Framework
  • 10. 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
  • 11. 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
  • 12. Adding an EDM to your projectDemo
  • 13. A design pattern to defer initialization until needed.EF 4 fixes a lot of problems with thisSupports Lazy LoadingOFF by defaultObjectContext setting, not application settingcontext.ContextOptions.DeferredLoadingEnabled=true;List<Thing> things = context.Things.ToList();foreach(var thing in things){varthingItems = thing.ThingItems}Entity FrameworkLazy Loading
  • 14. 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
  • 15. The context is the instance of the entityPassing an entity around to tiers breaks the contextV4 will handle this issue with “self-tracking” entitiesMake sure the context is always the sameEntity FrameworkContexts
  • 16. 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();
  • 17. 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();}
  • 18. 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
  • 19. 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
  • 20. 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
  • 22. James [email protected], @latringoInland Empire .NET User’s Groupwww.iedotnetug.org2nd Tuesday’s of each month in RiversideThank you