ASP.NET MVC and Entity Framework 4

23
ASP.NET MVC and Entity Framework Desert Code Camp Saturday, November 13, 2010 James Johnson Technical Evangelist

description

Slides from the November 2010 Desert Code Camp

Transcript of ASP.NET MVC and Entity Framework 4

Page 1: ASP.NET MVC and Entity Framework 4

ASP.NET MVC and Entity FrameworkDesert Code Camp

Saturday, November 13, 2010James Johnson

Technical Evangelist

Page 2: ASP.NET MVC and Entity Framework 4

• 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?

Page 3: ASP.NET MVC and Entity Framework 4

• 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

Page 4: ASP.NET MVC and Entity Framework 4

Demo

Page 5: ASP.NET MVC and Entity Framework 4

• 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

Page 6: ASP.NET MVC and Entity Framework 4

• 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

Page 7: ASP.NET MVC and Entity Framework 4

• 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

Page 8: ASP.NET MVC and Entity Framework 4

• 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 FrameworkDefinitions

Page 9: ASP.NET MVC and Entity Framework 4

Adding an EDM to your project

Demo

Page 10: ASP.NET MVC and Entity Framework 4

• 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 FrameworkLazy Loading

Page 11: ASP.NET MVC and Entity Framework 4

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 FrameworkEager Loading

Page 12: ASP.NET MVC and Entity Framework 4

• 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 FrameworkContexts

Page 13: ASP.NET MVC and Entity Framework 4

Entity FrameworkContexts

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();

Page 14: ASP.NET MVC and Entity Framework 4

Entity FrameworkContexts

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();}

Page 15: ASP.NET MVC and Entity Framework 4

• Very similar to LINQ to SQL• Major difference• LINQ 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

Page 16: ASP.NET MVC and Entity Framework 4

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

Page 17: ASP.NET MVC and Entity Framework 4

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 FrameworkLINQ to Entities

Page 18: ASP.NET MVC and Entity Framework 4

• 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

Page 19: ASP.NET MVC and Entity Framework 4

Repositories

• Add the two projects to your solution• Add references to your project

Page 20: ASP.NET MVC and Entity Framework 4

using GenericRepositorypublic class MyController{ private readonly IGenericRepository _repo; private readonly CourseEntities _db;

public MyController() { _repo = new EFGenericRepository.EFGenericRepository(_db); }}

Repositories

Page 21: ASP.NET MVC and Entity Framework 4

// 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

Page 22: ASP.NET MVC and Entity Framework 4

Questions?

Page 23: ASP.NET MVC and Entity Framework 4

James [email protected]://c1.ms/latringowww.speakerrate.com/latringohttp://bit.ly/latringo_dccTwitter, @latringo

Inland Empire .NET User’s Groupwww.iedotnetug.org2nd Tuesday’s of each month in Riverside, CA

Thank you