CHAPTER 1

image

Getting Started with Entity Framework

When working with relational databases, we think in terms of tables with rows and columns. Tables are highly structured and excel at set-based processing. Before the wide adoption of object-oriented programming, we thought about problems “procedurally” and solved them by writing code in a structured, top-down manner, function after function. Both worlds lined up well: Tables, rows, and columns closely matched the structured and procedural patterns in our code. Life was good - for a time ...

Much has evolved on the code side. We now think in terms of objects and domain models. We architect, design, and program against real-world things, like customers and orders. We draw nouns in our problem space on whiteboards. We draw lines between them, denoting relationships and interactions. We build specifications and assign work to development teams in terms of these drawings. In short, we architect, design, and program at a conceptual level that is very distant from the logical and physical organization of the database.

While the software development process has dramatically matured and the way in which we reason and solve problems has evolved, the database has not. The data remains locked in the same tables, rows, and columns paradigm, where it has been for many years. Unfortunately, this creates a mismatch (an impedance mismatch, as Microsoft fellow Anders Hejlsberg might call it): Object-oriented class hierarchies vs. a highly normalized database structure.

To cope with this gap, software projects often introduce a “database layer” that translates application domain classes into the rows and columns saved in tables. This approach has spawned many commercial and open-source data access frameworks; all attempting to bridge the ever widening gap between evolving development processes and structured data. Interestingly, an entire new field of Object Relational Mapping (ORM) has come out it.

The Entity Framework, coupled with the Language-Integrated Query (LINQ) framework, both from Microsoft, enables us to address the mismatch problem head-on. Using Entity Framework, we model entity classes for our application on a design surface or directly in code. Then we model relationships (associations) between these entities. In our code, we construct LINQ queries to program against these entities and associations. LINQ allows us to express relational database set concepts directly into our code while working in terms of entity types and associations. All of this helps to streamline our development experience while reducing the overall effort. Instead of coding large numbers of highly redundant ADO.NET data access constructs, we express our data needs in simple LINQ queries. Instead of programming against the schema of a highly normalized database, we code against entity classes. Entity Framework maps entity classes to the underlying database for you.

image Note  We use the term entity class or entity object to refer to a class that typically represents a domain item in an application. Domain classes represent real-world objects, such as an Employee, Department, or Manager, which your application will represent and track. The end users and stakeholders of your application should be able to look at the domain classes in your application and say, “Yes, that’s what our business does.” Entity classes define the schema, or properties, but not the behavior, of a domain class. In essence, entity classes expose the state of an object.

1-1. A Brief Tour of the Entity Framework World

Entity Framework is Microsoft’s strategic approach to data access technology for building software applications. Unlike earlier data access technologies, Entity Framework, coupled with Visual Studio, delivers a comprehensive, model-based ecosystem that enables you to develop a wide range of data-oriented applications, including desktop, Internet, cloud, and service-based applications, many of which will be covered in this book.

The History

Entity Framework is not new. The product dates back to Visual Studio 2008 and has come a long way in features and functionality. Figure 1-1 gives the pictorial history.

9781430257882_Fig01-01.jpg

Figure 1-1. A short history of the Entity Framework

The first version of Entity Framework was limited, featuring basic ORM support and the ability to implement a single approach known as Database First, which we thoroughly demonstrate in this book. Version 4 brought us another approach to using Entity Framework: Model First, along with full Plain Old CLR Object (POCO) support and default lazy loading behavior. Soon after, the Entity Framework team released three smaller, or point releases, 4.1 through 4.3, which represented yet another approach to using Entity Framework: Code First. As shown above, Version 5 of Entity Framework coordinated with the release of the .NET 4.5 framework and Visual Studio 2012, delivering significant performance improvements along with support for enums, table value functions, spatial types, the batch import of stored procedures, and deep support with the ASP.NET MVC framework.

Now we are at Version 6 of the Entity Framework. Version 6 delivers asynchronous support for querying and updates, stored procedure support for updates in Code First, improved performance, and a long list of new features, which we will focus on in this book.

image Note  Version 5 of Entity Framework can also be used with Visual Studio 2010. Version 6 of Entity Framework, released with Visual Studio 2013, has tooling/runtime support for Visual Studio 2012 and runtime support for Visual Studio 2010.

To level set, let’s take a brief look at some of the key components of the Entity Framework ecosystem. What follows is not by any means a comprehensive description of Entity Framework; that would take hundreds of pages. We’ll look at just a few key areas to help get you oriented for the recipes that are at the heart of this book.

The Model

Entity Framework is a technology with a strong focus on modeling. As you model with Entity Framework, you will see many familiar genetic markers from previous technologies and patterns. For example, you will, no doubt, see a resemblance to entity-relationship diagrams and the widely adopted conceptual, logical, and physical design layering approach.

The model that you create in Entity Framework is characterized by a construct called an Entity Data Model (EDM), which enables you to code against strongly typed entity classes, not database schema and objects. (Figure 1-2 shows this model in conceptual form.) The Entity Data Model enables you to customize the mappings between entity classes and database tables to move beyond the classic, one-to-one mapping, or class-to-table mapping.

9781430257882_Fig01-02.jpg

Figure 1-2. The Entity Data Model

In Figure 1-2, note how the database tables (on the left) do not directly map to the entity classes, which we code against (on the right). Instead, the mapping capabilities built into the Entity Data Model enable the developer to code against a set of entity classes that more closely resemble the problem domain, as opposed to a highly normalized database, designed for performance, scalability, and maintainability.

For example, note above how the Employees, Devices, and Phone numbers) are physically stored in three different tables, which from a DBA perspective makes perfect sense. But the developer codes against a single Employee entity class that contains a collection of Devices and Phone Numbers. From a developer and project stakeholder perspective, an employee is a single object, which happens to contain phone numbers and devices. The developer is unaware, and does not care, that the DBA has normalized this employee object into three separate database tables. Once configured, the mapping between the single class and three database tables is abstracted away and handled by the Entity Framework.

A reverse situation can be seen for the single Department table, which programmatically maps to three entity classes that represent individual departments. Again, to the developer and project stakeholders, a separate entity object represents each department (Accounting, Marketing, Finance, and so on), but DBA optimizes and collapses these objects into a single database table for data storage purposes.

Of course, as can be seen in the Location table, you can easily map a single entity class to a single database table, which is the default behavior for Entity Framework.

The key takeaway here is that developer and project stakeholders work with a representation of domain classes that make sense in the context of the application. The DBA can structure the underlying database tables in order to efficiently tune the database. And you can easily bridge these two worlds with the Entity Framework.

The Layers

The Entity Data Model consists of three separate layers: the conceptual, store, and mapping layers. Each layer is decoupled from the others.

The entity classes are contained in the conceptual layer of the Entity Data Model. This is layer in which developers and project stakeholders work. Depending upon how you implement the Entity Framework, the conceptual layer can be modeled with a designer or from code. Once you make that decision, you can reverse- engineer your model from an existing database, leveraging the designer and extensive tooling that ships with Entity Framework or create your model with code and have Entity Framework generate the database for you. The syntax for the conceptual layer is defined in the Conceptual Schema Definition Language (CSDL).

Every useful application needs to persist objects to some data store. The store layer of the Entity Data Model defines the tables, columns, relationships, and data types that map to the underlying database. The Store Schema Definition Language (SSDL) defines the syntax for the store model.

Finally, the mapping layer defines the mapping between the conceptual and store layer. Among other things, this layer defines how properties from entity classes map to columns in database tables. This layer is exposed to the developer from the Mapping Details window contained in the Entity Framework designer or data annotations and fluent API if choosing a code-based approach. The Mapping Specification Language (MSL) defines the syntax for the mapping layer.

The Terminology

As expected, the Entity Framework comes with its own vocabulary. If you have used any of the popular ORM tools or are familiar with database modeling, you’ve probably encountered some of the terminology before. Although the entire vocabulary is extensive, we’ll provide just a few of the basic terms to get us started.

As discussed earlier, an EntityType represents a class in your domain model. An instance of an EntityType is often referred to as an entity. If you are using the Entity Framework designer, an EntityType is represented on the design surface as a box with various properties. Figure 1-3 shows two EntityTypes: Employee and Task.

9781430257882_Fig01-03.jpg

Figure 1-3. A model with Employee and Task with a one-to-many association between them

An EntityType usually has one or more properties. Just like with a class, a property is a named value with a specific data type. Properties can have simple types like integer, string, and so on; or have ComplexTypes; or be collections. Navigation properties refer to other related entities (typically represented by foreign key relationships in a database). The non-navigation properties on an EntityType are usually just called scalar properties.

A relationship between two entities is called an association. Associations between EntityTypes are shown on the design surface as a line connecting the EntityTypes. The line is annotated to show the multiplicity on each end of the association. The association in Figure 1-3 is a one-to-many association between Employee and Task. An Employee can have zero or more tasks. Each Task is associated to exactly one Employee.

Every EntityType has a property or set of properties that denote its EntityKey. An EntityKey uniquely identifies the entity to Entity Framework and is most often mapped to a primary key from the entity’s representation in the underlying database.

Finally, no discussion on Entity Framework would be complete without mentioning the context object. The context object for Entity Framework is your gateway into the Entity Framework services. The context object exposes entity objects, manages the database connection, generates parameterized SQL, marshals data to and from the database, caches objects, helps maintain change tracking and materializes, or transforms, an untyped result set into a collection of strongly typed objects.

In the beginning, there was the ObjectContext object. Now, Entity Framework supports an alternate, more streamlined context object called the DbContext. The DbContext greatly simplifies the developer experience when working with Entity Framework. Interestingly, the DbContext is a wrapper, or facade, around the ObjectContext, exposing the underlying ObjectContext functionality in an intuitive, friendly and productive way.

Clearly, the DbContext is the preferred approach for working with Entity Framework as we will demonstrate in great detail in this book.

The Code

Despite a tremendous emphasis on visual design support, the Entity Framework is all about code. The models, EntityTypes, associations, mappings, and so on are ultimately expressed in concrete code that becomes part of your application. This code is either generated by Visual Studio and Entity Framework or created manually by the development team. You can choose quite a bit about the code-generation process or the lack of it by changing various properties on your project or modifying the underlying code-generation templates.

Visual Studio uses a code-generation technology called Text Template Transformation Toolkit, simply referred to as T4 templates. The Visual Studio tooling uses T4 templates to generate, or scaffold, code automatically. The great thing about T4 template support in Visual Studio is that you can edit the templates to tailor the code-generation process to match your exact needs. This is an advanced technique, but it is necessary in some cases. We’ll show you how to do this in a few recipes.

Alternatively, you can leverage the more recent Code-First approach to manually create the concrete code yourself, gaining direct control over the entire process. With Code First, the developer can create entity classes, mappings and context object, all without the help of a designer. These manually created entity classes, commonly referred to as POCO, or Plain Old CLR Objects, have no dependence on Entity Framework plumbing. Even more interesting, the development team can leverage the Entity Framework Power Tool utilities (free download from Microsoft) to reverse-engineer a Code First model from an existing database, foregoing the effort to have manually create the entity classes, mappings and context object. The recipes in Chapter 8 show you the basics of creating and using POCO. Many of the recipes throughout the book will show you how to use Code First across specific contexts such as in n-Tier applications.

Visual Studio

Of course, the main tool we use when developing applications for the Windows environment is Visual Studio. This Integrated Development Environment has evolved over many years from a simple C++ compiler and editor to a highly integrated, multi-language environment that supports the entire software development lifecycle. Visual Studio and its related tools and services provide for design, development, unit testing, debugging, software configuration management, build management and continuous integration, and much more. Don’t be worried if you haven’t used all these in your work; few developers have. The point is that Visual Studio is a full-featured toolset. Visual Studio plays a vital role in the development of Entity Framework applications.

Visual Studio provides an integrated design surface for Entity Framework models. Using this design surface and other tools in Visual Studio, you can create models from scratch or create them from an existing database. You also have the option to completely eliminate the designer and manually craft your Entity Types and configuration.

If you have an existing database, which is the case for many of us with existing applications, Visual Studio provides tools for importing your tables and relationships into a model. This fits nicely with the real world because few of us have the luxury of developing brand-new applications. Most of us have to extend, maintain, and evolve our existing code and databases.

Alternately, you can create a model from scratch by starting with an empty design surface and adding new EntityTypes to the surface, creating both associations and inheritance hierarchies for your model. When you are done creating the model, right-click the design surface and select Generate Database from Model.

If your project team is code-centric, you can instead create a set of domain classes, including relationships and a context class and then wire up these classes to hook into the Entity Framework engine and features without having to use a designer.

Once you have created your model, changes often happen. That’s the nature of software development. Visual Studio provides tools for updating the model from the database. This will keep the model synchronized with changes in the database. Additionally, the Entity Framework Team also supports a tool called Code First Migrations , which can be used to keep your database up-to-date with changes in your model.

1-2. Using Entity Framework

Entity Framework is tightly integrated with Visual Studio. To implement Entity Framework in your application, add a new ADO.NET Entity Data Model in your project. Right-click your project and select Add arrow.jpg New Item. In the dialog box (see Figure 1-4), choose the ADO.NET Entity Data Model template. This template is located under the Data templates. Click Add to launch the Entity Data Model Wizard.

9781430257882_Fig01-04.jpg

Figure 1-4. Adding a new model to your project

There are two options on the first page of the Entity Data Model Wizard: start with an existing database or start with an empty model. (The former option is actually labeled “Generate from database.”) This first page is shown in Figure 1-5.

9781430257882_Fig01-05.jpg

Figure 1-5. The Entity Data Model Wizard gives you a choice between creating a model from an existing database or starting with an empty model

Generating a model from an existing database is the Database-First approach. From the tables, views, and stored procedures that you select from the underlying database, the wizard will create a model and entity classes, against which you can write code. The immediate benefit here is that you write code against strongly typed entity classes, which Entity Framework maps to the underlying database tables and columns. If the tables you include are related in the database, these relationships will be modeled as associations. This is one way to create your model if you already have a database for your application. However, if you prefer to use the Code-First approach with an existing database, worry not. The Entity Framework team has created tooling (The Entity Framework Power Tools) that reverse-engineers an existing database into domain entity classes, just as if you coded them by hand.

If you’re working on a brand-new application, without an existing database, you have options as well. In the Entity Framework designer, you can start with an empty design surface. Right-click the design surface to create new EntityTypes, associations, or inheritances. You can also drag them from the Toolbox onto the design surface. Once your model is complete, just right-click the design surface and select Generate Database from Model. This will generate a script you can use to create the database tables and relationships for the model.

Alternately, you can manually create each of your entity classes in Visual Studio and simply register them in the DbContext object, then hook into the Entity Framework services. Entity Framework will map the classes to the underlying databases and automatically create a model in memory at runtime.

With the Model-First or Database-First approaches, you use the Entity Framework designer to develop your model. The key parts of a model in the designer are shown in Figure 1-6. In this model, a Customer has a one-to-many association with an Order. Each customer may have many orders, but each order is associated with just one customer. The Mapping Details window shows that the Customer EntityType maps to the Customer table in the database. The Mapping Detail window also shows the mapping between the columns in the Customer table and the scalar properties in the Customer EntityType. Keep in mind that you can make the same kind of mapping configurations using the data annotations or fluent API features found in the Code First approach to using Entity Framework.

9781430257882_Fig01-06.jpg

Figure 1-6. Key parts of a model in the designer

Of course, there’s more to the designer and model than just the few key parts illustrated in Figure 1-6. In the recipes in this book, we’ll cover just about every aspect of using the designer to create models. In some cases, we go beyond what can be done with the designer and show you how to create models that require direct editing of the underlying .edmx file. The .edmx file contains the complete model definition, including the conceptual layer, store layer, and mapping layer.

So, whether we implement Entity Framework with the Database-First, Model-First or Code-First approach, we always end up with a model. We gain significant productivity, as we can program against objects in the model (EntityTypes) as you do with other objects in your application. For the model in Figure 1-6, your code uses Customer and Order in much the same way as you use other objects.

If you want to insert a new customer and order into the database, you can create instances of the Customer and Order types, set the properties, add them to the in-memory context that represents the model, and call SaveChanges(). All the necessary SQL code is generated and sent to the database to insert the rows. To retrieve customers and orders from the database, you use either LINQ or Entity SQL to create a query in terms of the EntityTypes and associations in the model.

The recipes throughout this book will show you step by step how to model just about every conceivable database scenario; how to query, insert, update, and delete using these models; and how to use Entity Framework in many kinds of applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset