350 likes | 466 Views
Data Modeling Seminar. February 18 , 2012 Lesson 6 Data Access Layering – Part 2 Entity Framework v4.0. What You Just Learned. What You Just Learned Microsoft built into Entity Framework . The Essentials.
E N D
Data ModelingSeminar February 18, 2012 Lesson 6 Data Access Layering – Part 2 Entity Framework v4.0
What You Just Learned • What You Just Learned • Microsoft built into Entity Framework
The Essentials • The Entity Framework bridges the gap between how developers commonly manipulate conceptual objects and the way data is actually stored (records in database tables). • The technical term for a tool that provides this abstraction is object relational mapper (ORM). • ORMs help developers be more efficient and focused.. • It also means that the code is more portable – switching database software requires changing a setting in the ORM, not a rewrite of the whole codebase to match the new database's dialect.
Getting Started • One of the nice features of using the Entity Framework is its out-of-the-box simplicity. • It does not need a download, install, or patch anything to get started with my first EF app. • Boot up VS 2010, open a new project, design entities, and write code, then off you go. • Follows is a step-by-step walkthrough. A simple events calendar.
Walkthrough • Begin by opening Visual Studio 2010.
Walkthrough • From the 'File' menu select 'New' >> 'Project'.
Walkthrough • Visual Studio will now set up a basic C# application
Walkthrough • The next step is adding your entities to the project. • To do this, we’ll need to add a new file to our project which will contain the specifications for our entities. • Open up the Solution Explorer panel. • Right-click on the name of your application • Click on the option 'Add' >> 'New Item'. • Select 'ADO.NET Entity Data Model'.
Walkthrough • If you are starting an application from scratch, select 'Empty model.' • This is known as the model-first approach, instead of the database-first approach • If there was already a database in place, then you would select the 'Generate from database' option • The Entity Framework would do its best to create models and associations that fit the data.
Walkthrough • Let’s start with the model-first approach.
Walkthrough • This will now open a new file – a canvas onto which you can design your data model. • Rather than having to directly write the underlying XML file to specify the models and properties, this designer is a pretty slick way to configure your models and associate them. • You start with an empty canvas.
Walkthrough • To add an entity, right-click on the design surface (the white canvas area) and click 'Add' >> 'Entity' from the context menu. • Type a name for the entity, and notice how it automatically attempts to pluralize it in the EntitySet field. • EntitySetsare collections of entities (that map to tables in the database), which allow you to add, delete, or update entities (rows in the database). • Although the system usually gets the pluralizing right, you can tweak it as you please.
Walkthrough • The next step will be to add properties to that entity. • Properties are essentially "instance data" in the lexicon of object-oriented programming or "columns" in database parlance. • You can add a property to an entity by right-clicking the entity and selecting 'Add' >> 'Scalar Property'. • When you add the property, you can then name it whatever makes sense.
Walkthrough • Add an association between the Event and the User to represent which User created an Event. • To do this, right click anywhere on the design surface and select 'Add' >> 'Association'.
Walkthrough To configure the association: • Select the two “ends” of the association, or the two entities you will be associating, and their multiplicity to match the association you have in mind. • In this example, setting up a many-to-one association between an Event and its creator; each Event has only one creator, but each User may have created many Events. • Name this “EventCreator” to be specific about what this association represents and avoid collisions or ambiguity.
Walkthrough To configure the association: • Customize the navigation properties using terms that make sense relative to this relationship. • In this example, use the terms ‘Creator’ and ‘CreatedEvents.’ • These are the property names used by one entity to get to the other. • One would use Event.Creator to get the single User who created that event and User.CreatedEvents for a list of events created by a certain User
Walkthrough • Once the entities are ready: • Right click the canvas and select 'Generate Database from Model.'
Walkthrough • Now let’s create a model from an existing database. • Open up the Solution Explorer panel. • Right-click on the name of your application • Click on the option 'Add' >> 'New Item'. • Select 'ADO.NET Entity Data Model'.
Walkthrough • After a small wait, you should now have a model of your database complete with all scalar properties, navigational properties, and associations.
Walkthrough • Build Model Context ClassScheduleEntitiesctx = newClassScheduleEntities() • Access Entities in the Model Context • using (ClassScheduleEntitiesctx = newClassScheduleEntities()) • { • var courses = ctx.Courses.ToList(); • foreach (Course c in courses) • { • Console.WriteLine(c.CourseId.ToString()); • } • }
Walkthrough This query retrieves all Courses andtheir related Department in a single query. EF 4 introduces the ability to load related Entities “on demand”: • using (ClassScheduleEntitiesctx = newClassScheduleEntities()) • { • varcourses = ctx.Courses.ToList(); • intid = courses.First().Department.DepartmentId; • } Without lazy loading, the code above would throw a NullReferenceException because the Department was neither pulled in with Include(), nor loaded explicitly with Load(). EF 4 allows the code above to “automatically” query for the related Department if it is not already loaded. Lazy loading is “on” by default.
Walkthrough There’s a caveat here. Take a gander: • using (ClassScheduleEntitiesctx = newClassScheduleEntities()) • { • var courses = ctx.Courses.ToList(); • foreach (Course c in courses) • { • Console.WriteLine(c.Department.DepartmentId.ToString()); • } • } This is a case where lazy loading can get you into trouble. Suppose there were 100 Courses in the courses List<Course>. The code above would result in 100 additional queries, one for each Course in the list. This can get even worse in the case of one-to-many relationships.
Lab 5 • Entity Framework 4.0 Demonstration