programming4us
programming4us
WEBSITE

Advanced ASP.NET : The Entity Framework (part 2)

6/23/2011 4:20:29 PM

2. The Data Model Diagram

The .edmx model file is actually a lengthy XML document that details the structure of your database. For example, it lists all the tables you chose to include, their data types, the relationships, and so on. This is the essential information that your application needs to manipulate the model. The .edmx file doesn't contain any data—that's left stored safely in the database.

Although you can view the .edmx file in a text editor, the XML is too complex and detailed to be worth editing by hand. Instead, Visual Studio provides a visual designer that represents the content in the .edmx file using a sprawling diagram of database tables. To see this designer, simply double-click your .edmx file in the Solution Explorer. Figure 4 shows part of the entity data model for the Northwind database.

Figure 4. Part of the Northwind entity data model

Here's a quick guide to understanding the data model diagram:

  • Each box in the data model is an entity, which corresponds to a table in the database.

  • Each entity includes two types of properties. The first are the data properties—they correspond to the fields in the actual table. The second are navigation properties—they are a coding convenience that allows you to step from one table to the related records in another table .

    If your tables are stuffed full of properties, the data model diagram can quickly get cluttered. In this case, you can hide a table's property list by clicking the up-pointing arrow in the top-right corner of the table box. This collapses the table box so it shows the table name only. Click the top-right corner again to expand it.


  • The dotted lines between the tables indicate relationships.

Using the entity data model designer, you can refine your data model. Although you're able to change virtually every detail, some customizations are easier and more useful than others.

Here are some of the basic changes you can make:

Rearrange the entities:

Most people start by dragging around the entities on their diagram. This doesn't change the way your model works, but it may make it easier for you to survey the overall structure of your database.

Delete entities you don't need:

Just select the entities and press the Delete key. (Don't worry, you can always add them back later by updating your data model.) You can do the same thing to remove unnecessary fields, but this general isn't worth the trouble—and it risks removing some important information from the reach of your application.

NOTE

When you make changes to a data model, such as deleting and renaming items, these changes affect the model, not your database.

Rename entities:

Just double-click the entity name and type in something better. This changes the name you use in code, but the Entity Framework is smart enough to keep querying the original table in the database. For example, if you have a table like pub_info (in the Pubs sample database), you can use this trick to give it a more code-friendly moniker, like PublicationInfo.

Rename fields:

As every database designer knows, once a database is live and in use, you can't risk renaming its fields or objects. Sometimes, that means you'll need to accept cryptic or misrepresentative field names. However, you can rename them in your model and simplify your code—just right-click the field and choose Rename.

Some developers prefer to never rename so their data model closely matches the database reality. This can help avoid possible confusion (for example, you won't need to look up the real field names to write a stored procedure). But if you go wild with field renaming, it's important to realize that there is a quick way to review the original names. Just right-click a table and choose Table Mapping to pop open a window that lists the underlying field name for each property (Figure 5).


Figure 5. Renamed fields in the Table Mapping window

Change field properties:

Although this is too specialized for most developers, there are a number of details you can tweak using the Properties window, including the data type of each property, its default value, whether it has a fixed length, whether it allows nulls, and so on. Usually, these details are drawn from the database, but to supplement them, just right-click a field and choose Properties.

3. Updating a Data Model

At some point, you may need to add to your model or refresh it to take into account changes that have been made to the database. Fortunately, the Entity Framework makes this task easy. Just right-click anywhere in your model, and choose Update Model From Database. You'll see a dialog box named Update Wizard, even though it has just one step (Figure 6).

Figure 6. Adding a table to the data model

In the Update Wizard are three tabs:

Add:

This tab allows you to add new database objects to your model. You choose which objects you want to add by checking the corresponding check box, just as you did when you first created the model.

Refresh:

This tab simply lists the database objects that are currently in your model (and in the back-end database). As part of the update process, Visual Studio will check all these objects for changes and regenerate them. All of this happens without disturbing the customizations you've made (such as field name mapping).

Delete:

This tab lists the database objects that are in your model but are no longer in the database. When you perform the update, Visual Studio will remove these from your model altogether.

When you've picked the new objects you want from the Add tab and reviewed the information in the Refresh and Delete tabs, click Finish to perform the update.

Visual Studio provides a nifty tool that lets you do the reverse trick and generate a database based on a data model. You could use this trick to re-create a database on another computer, or you could use the data model designer to create a new data model and then use that data model to build a new database. To try this feature, right-click anywhere on the data model designer and choose Generate Database from Model.


4. The Data Model Code

The data model designer is pretty slick, but to actually use your data model, you need the help of some behind-the-scenes code. Like the data model XML, this code is long and tedious, so you won't want to read it through from start to finish. However, you'll have a better understanding about how your application works if you review its basic design and organization.

All the data model code is contained in a .Designer.vb file in the App_Code folder. (In the current example, it's Northwind.Designer.vb .)

All the code is placed in a namespace that has the name of your data model, plus the word Model, as in NorthwindModel. If you look through the code, you'll make a few observations immediately.

First, you'll notice that there are attributes (bits of descriptive information in angled brackets) scattered throughout. These attributes connect various pieces of code to the back-end database they represent. For example, consider this attribute:

<EdmEntityTypeAttribute(NamespaceName:="NorthwindModel", Name:="Employee")> _

It connects the following Employee class to the Employee table in the data model. Although attributes like these are critically important to the functioning of the Entity Framework, you don't need to pay any attention to them yourself.

The next design detail you'll notice is that the code is split into two regions: entities and contexts. Regions are simply an organization feature that lets you temporarily collapse blocks of code out of sight. However, the regions in the data model underscore the two types of classes that the Entity Framework uses.

4.1. Entities

The entities are the data objects—classes that represent the records from your database. The Entity Framework uses a separate entity class for each table, and in the Northwind database example you'll have classes like these: Customer, Product, Order, Order_Detail, Employee, Shipper, Region, and so on. They all derive from a base class called EntityObject, which gives them support for change tracking and other Entity Framework features.

As you saw in the data model, each entity class has the same basic structure. It consists of data properties (also known as primitive properties) that correspond to fields and navigation properties that let you find related data. For example, the Employee class has data properties such as FirstName, LastName, and EmployeeID. It also navigation properties like Orders and Territories.

If you dig deeper into the property procedure code, you'll find quite a bit of boilerplate code for tracking changes, raising events, and communicating with the inner mechanics of the Entity Framework. Finally, each entity class also includes a shared factory method that lets you create a new, completely and correctly initialized entity object. For example, you can call Employee.CreateEmployee() and pass in the appropriate parameters to create a new employee object, as you'll see shortly.

4.2. Contexts

While the entities take care of representing the data, the context takes care of the data access—the code that fetches the records you want from the database and commits changes when you're ready. Each database requires a separate context class, which means the Northwind data model example gets just one context. It's called NorthwindEntities, and it derives from a base class called ObjectContext.

The context class includes a collection for every table in your database. For example, in the NorthwindEntities class you'll have an Employees property that returns a collection of Employee entity objects, a Products property that returns a collection of Product objects, and so on. These properties are the starting point for working with your data model. For example, if you retrieve and display a collection of Product objects through the Products property (as shown in the next section), the Entity Framework quietly contacts your database, queries the Products table, and creates the objects you need. It then keeps them cached in memory so you don't need to repeat the trip again (at least not until the next postback).

NOTE

Unlike the data model diagram, you should not change any of the data model code, because your changes will be wiped out when the database changes and you refresh the data model. It is possible to extend the data model by writing partial classes (in another file) that add on to the automatically generated classes that Visual Studio creates. However, this is an advanced technique that's not recommended unless you have plenty of Entity Framework experience and a specific goal in mind (for example, you want to add built-in property validation to your entities).

Other  
 
PS4 game trailer XBox One game trailer
WiiU game trailer 3ds game trailer
Top 10 Video Game
-   F1 2015 | Features Trailer
-   Battle Fantasia Revised Edition | Debut Trailer for Steam
-   Victor Vran [PC] Story Trailer
-   Star Wars Battlefront PC Alpha footage
-   Skyforge [PC] Open Beta Gameplay Trailer
-   Armored Warfare [PC] PvE Trailer
-   F1 2015 [PS4/XOne/PC] Features Trailer
-   Act of Aggression [PC] Pre-Order Trailer
-   Sword Coast Legends [PC] Campaign Creation E3 2015 Trailer
-   Sword Coast Legends [PC] Campaign Creation E3 2015 Dungeon Run Trailer
-   Naruto Shippuden: Ultimate Ninja Storm 4 Trailer
-   Danganronpa Another Episode: Ultra Despair Girls Trailer 2
-   Project X Zone 2 Trailer
-   Poly Bridge Early Access Trailer
-   Rodea The Sky Soldier Trailer
Game of War | Kate Upton Commercial
programming4us
 
 
programming4us