This will start the Entity Data Model Wizard
that will help you get started building an Entity
Framework model.
This will show the dialog shown in Figure 29-2
that enables you to select whether you want to
automatically create a model from a database
(Generate from Database), or start with an empty
model (Empty Model).
The Empty Model option is useful when you want
to take the approach of creating your model from
scratch, and either mapping it manually to a given
database, or letting the Entity Framework create a
database based on your model.
However, as previously stated you will be creating an
entity model from the AdventureWorksLT database,
so for the purpose of this example use the Generate
from Database option, and get the wizard to help you
create the entity model from the database.
Moving onto the next step, you now need to
create a connection to the database (as shown
in Figure 29-3). You can find the most recent
database connection you’ve created in the
drop-down list, but if it’s not there (such as if
this is the first time you’ve created a connection
to this database) you will need to create a new
connection. To do so, click the New Connection
button and go through the standard procedure of
selecting the SQL Server instance, authentication
credentials, and finally, selecting the database.
fiGure 29-2
fiGure 29-3
626
.
chaPter 29 The Ado.neT enTiTy FrAmeWork
If you are using a username and password as your authentication details, you can choose not to
include those in the connection string (containing the details required to connect to the database)
when it is saved, because this string is saved in
plain text that would enable anyone who sees it to
have access to the database. In this case you would
have to provide these credentials to the model before
querying it in order for it to create a connection
to the database. If you don’t select the checkbox
to save the connection settings in the App.config
file you will also need to pass the model the details
on how to connect to the database before you can
query it.
In the next step, the wizard uses the connection
created in the previous step to connect to the
database and retrieve its structure (that is, its tables,
views, and stored procedures), which is displayed in
a tree for you to select the elements to be included
in your model (see Figure 29-4).
Other options that can be specified on this screen include:
.
Pluralize or Singularize Generated Object Names: This option (when selected) intelligently
takes the name of the table/view/stored procedure and pluralizes or singularizes the name
based on how that name is used in the model (collections will use the plural form, entities
will use the singular form, and so on).
.
Include Foreign Key Columns in the Model: The previous version of the Entity Framework
did not create properties for foreign key columns in the entities — opting to create a
relationship instead. However, in numerous scenarios this was not ideal, making it messy
to do some simple tasks due to the absence of these properties. In this new version you can
now select to include them in your entities by selecting this option.
.
Model Namespace: This enables you to specify the namespace in which all the classes
related to the model will be created. By default, the model will exist in its own namespace
(which defaults to the name of the model entered in the Add New Item dialog) rather than
the default namespace of the project to avoid conflict with existing classes with the same
names in the project.
Select all the tables in the database to be included in the model. Clicking the Finish button in this
screen creates an Entity Framework model that maps to the database. From here you can view the
model in the Entity Framework and adjust it as per your requirements and tidy it up as per your
tastes (or standards) to make it ideal for querying in your code.
the entity framework designer
Once the Entity Framework model has been generated, it opens in the Entity Framework designer,
as shown in Figure 29-5.
fiGure 29-4
Creating an entity Model .
627
fiGure 29-5
You’ll note that the designer has automatically laid out the entities that were created by the wizard,
showing the associations it has created between them.
You can move entities around on the designer surface, and the designer will automatically move the
association lines and try and keep them neatly laid out. Entities will automatically snap to a grid,
which you can view by right-clicking the designer surface and selecting Grid . Show Grid from the
context menu. You can disable the snapping by right-clicking the designer surface and unchecking
Grid . Snap to Grid from the context menu to have finer control over the diagram layout, but you
will find that entities line up better (and hence make the diagram neater) by leaving the snapping on.
As you move entities around (or add additional entities to) the diagram, you may find it gets a little
messy, with association lines going in all directions to avoid getting “tangled.” To get the designer
to automatically lay out the entities neatly again according to its own algorithms, you can right-click
the designer surface and select Diagram . Layout Diagram from the context menu.
Entity Framework models can quickly become large and difficult to navigate in
the Entity Framework designer. Luckily, the designer has a few tools to make
navigating it a little easier. The designer enables you to zoom in and out using
the zoom buttons in its bottom-right corner (below the vertical scrollbar — see
Figure 29-6). The button sandwiched between these zoom in/out buttons zooms
to 100% when clicked.
To zoom to a predefined percentage, right-click the designer surface and select one of
fiGure 29-6
the options in the Zoom menu. In this menu you will also find a Zoom to Fit option
(to fit the entire entity model within the visible portion of the designer), and a Custom option that
pops up a dialog enabling you to type a specific zoom level.
628 .
chaPter 29 The Ado.neT enTiTy FrAmeWork
In addition, selecting an entity in the Properties tool window (from the drop-down object selector)
automatically selects that entity in the designer and brings it into view; right-clicking the entity in
the Model Browser tool window (described shortly) and selecting the Show in Designer menu item
does the same. These make it easy to navigate to a particular entity in the designer, so you can make
any modifications as required.
You can minimize the space taken by entities
by clicking the icon in the top-right corner
of the entity. Alternatively, you can roll
up the Properties/Navigation Properties
groupings by clicking the +/– icons to their
left. Figure 29-7 shows an entity in its
normal expanded state, with the Properties/
Navigation Properties groupings rolled up
and completely rolled up.
You can expand all the collapsed entities in one go by right-clicking the designer surface and
selecting Diagram . Expand All from the context menu. Alternatively, you can collapse all the
entities in the diagram by right-clicking the designer surface and selecting Diagram . Collapse All
from the context menu.
A visual representation of an entity model (as provided by the Entity Framework designer) can
serve a useful purpose in the design documentation for your application. The designer provides a
means to save the model layout to an image file to help in this respect. Right-click anywhere on the
designer surface and select Diagram . Export as Image from the context menu. This pops up the
Save As dialog for you to select where to save the image. Note that it defaults to saving as a bitmap
(.bmp) — if you open the Save As Type drop-down list you will find that it can also save to JPEG,
GIF, PNG, and TIFF. PNG is probably the best choice for quality and file size.
It can often be useful (especially when saving a diagram for documentation) to display the property
types against each property for an entity in the designer. You can turn this on by right-clicking
the designer surface and selecting Scalar Property Format . Display Name and Type from the
context menu. You can return to displaying just the property name by selecting the Scalar Property
Format . Display Name item from the right-click context menu.
As with most designers in Visual Studio, the Toolbox and Properties tool
windows are integral parts of working with the designer. The Toolbox (as
shown in Figure 29-8) contains three controls: Entity, Association, and
Inheritance. How to use these controls with the designer is covered shortly.
The Properties tool window displays the properties of the selected item(s)
in the designer (an entity, association, or inheritance), enabling you to
modify their values as required.
In addition to the Toolbox and Properties tool windows, the Entity Framework designer also
incorporates two other tool windows specific to it — the Model Browser tool window and the
Mapping Details tool window — for working with the data.
fiGure 29-7
fiGure 29-8
Creating an entity Model .
629
The Model Browser tool window (as shown
in Figure 29-9) enables you to browse the
hierarchy of both the conceptual entity model
of the database and its storage model. Clicking
an element in the Store model hierarchy shows
its properties in the Properties tool window;
however, these can’t be modified (because
this is an entity modeling tool, not a database
modeling tool). The only changes you can
make to the Store model is to delete tables, views, and stored procedures (which won’t modify the
underlying database). Clicking elements in the Conceptual model hierarchy also shows their properties
in the Properties tool window (which can be modified), and its mappings are displayed in the Mapping
Details tool window. Right-clicking an entity in the hierarchy and selecting the Show in Designer
menu item from the context menu brings the selected entity/association into view in the designer.
The second picture in Figure 29-9 demonstrates the searching functionality available in the Model
Browser tool window. As previously discussed, because your entity model can get quite large, it can
be difficult to find exactly what you are after. Therefore, a good search function is very important.
Type your search term in the search textbox at the top of the window and press Enter. In this
example the search term was Address, which highlighted all the names in the hierarchy (including
entities, associations, properties, and so on) that contained the search term. You’ll note that the
vertical scrollbar has the places in the hierarchy (which has been expanded) highlighted where
the search terms have been found, making it easy to see where the results were found throughout
the hierarchy. The number of results is shown just below the search textbox, next to which are an
up arrow and a down arrow to enable you to navigate through the results. When you are finished
searching you can click the cross icon next to these to return the window to normal.
The Mapping Details tool window (as shown in Figure 29-10) enables you to modify the mapping
between the conceptual model and the storage model for an entity. Selecting an entity in the
designer, the Model Browser tool window, or the Properties tool window shows the mappings in
this tool window between the properties of the entity to columns in the database. You have two
ways of mapping the properties of an entity to the database: either via tables and views, or via
functions (that is, stored procedures). On the left side of the tool window are two icons, enabling
you to swap the view between mapping to tables and views, to mapping to functions. However,
we’ll focus here just on the features of mapping entity properties to tables and views.
fiGure 29-9
fiGure 29-10
630 .
chaPter 29 The Ado.neT enTiTy FrAmeWork
The table/view mapping has a hierarchy (under the Column column) showing the table(s) mapped to
the entity, with its columns underneath it. To these columns you can map properties on your entity
(under the Value/Property column) by clicking in the cell, opening the drop-down list that appears,
and selecting a property from the list.
A single entity may map to more than one database table/view (bringing two or more tables/views
into a single entity, as previously discussed). To add another table/view to the hierarchy to map to
your entity, click in the bottom row where it says <Add a Table or View> and select a table/view
from the drop-down list. When you add a table to the Mapping Details tool window for mapping
to an entity, it automatically matches columns with the same name to properties on the entities and
creates a mapping between them. Delete a table from the hierarchy by selecting its row and pressing
the Delete key.
Conditions are a powerful feature of the Entity Framework that enable you to selectively choose
which table you want to map an entity to at run time based on one or more conditions that you
specify. For example, say you have a single entity in your model called Product that maps to a table
called Products in the database. However, you have additional extended properties on your entity
that map to one of two tables based on the value of the ProductType property on the entity — if
the product is of a particular type it will map the columns to one table, if it’s another type it will
map the columns to the other table. You can do this by adding a condition to the table mapping. In
the Mapping Details window click in the row directly below a table to selectively map where it says
<Add a Condition>. Open the drop-down list that appears, which will contain all the properties
on the entity. Select the property to base your condition on (in the given example it would be the
ProductType property), select an operator, and enter a value to compare the property to. Note that
there are only two operators: equals (=) and Is. You can add additional conditions as necessary to