determine whether the table should be used as the source of the data for the given properties.
Note that a number of advanced features are available in the Entity Framework,
but not available in the Entity Framework designer (such as working with the store
schema, annotations, referencing other models, and so on). However, these actions
can be performed by modifying the schema files (which are XML files) directly.
creating/Modifying entities
The Entity Data Model Wizard gave you a good starting point by building an entity model for
you. In some cases this may be good enough and you can start writing the code to query it, but you
can now take the opportunity to go through the created model and modify its design as per your
requirements.
Because the Entity Framework is providing you with a conceptual model to design and work with,
you are no longer limited to having a 1:1 relationship between the database schema and an object
model in code, so the changes you make in the entity model won’t affect the database in any way.
So you may wish to delete properties from entities, change their names, and so on, and it will
have no effect on the database. In addition, because any changes you make are in the conceptual
model, updating the model from the database will not affect the conceptual model (only the
storage model), so your changes won’t be lost.
Creating an entity Model .
631
Changing Property names
Often you will find yourself working with databases that have tables and columns containing prefixes
or suffixes, over/under use of capitalization, or even names that no longer match their actual function.
This is where the use of an ORM like the Entity Framework can demonstrate its power, because
you can change all of these in the conceptual layer of the entity model to make the model nice to
work with in code (with more meaningful and standardized names for the entities and associations),
without needing to modify the underlying database schema. Luckily, the tables and columns in the
AdventureWorksLT database have reasonably friendly names, but if you wanted to do so it would
simply be a case of double-clicking the property in the designer (or selecting it and pressing F2), which
changes the name display to a textbox enabling you to make the change. Alternatively, you can select
the property in the designer, the Model Browser tool window, or the Properties tool window, and
update the Name property in the Properties tool window.
adding Properties to an entity
Let’s now look at the process of adding properties to an entity. Three types of properties exist:
.
Scalar properties: Properties with a primitive type, such as string, integer, Boolean,
and so on.
.
Complex properties: A grouping of scalar properties in a manner similar to a structure in
code. Grouping properties together in this manner can make your entity model a lot more
readable and manageable.
.
Navigation properties: Used to navigate across associations. For example, the
SalesOrderHeader entity contains a navigation property called SalesOrderDetails that
enables you to navigate to a collection of the SalesOrderDetail entities related to the current
SalesOrderHeader entity. Creating an association between two entities automatically creates
the required navigation properties.
The easiest way to try this for yourself is to delete a property from an existing entity and add it
back again manually. Delete a property from an entity (select it in the designer and press the Delete
key). Now to add it back again, right-click the entity and select Add . Scalar Property from the
context menu. Alternatively, a much easier and less frustrating way when you are creating a lot of
properties is to simply select a property or the Properties header and press the Insert key on your
keyboard. A new property will be added to the entity, with the name displayed in a textbox for you
to change as required.
The next step is to set the type of the property, for which you’ll have to move over to the Properties
tool window to set. The default type is string, but you can change this to the required type by
setting its Type property.
Properties that you want to designate as entity keys (that is, properties that are used to uniquely
identify the entity) need their Entity Key property set to True. The property in the designer will have
a picture of a little key added to its icon, making it easy to identify which properties are used to
uniquely identify the entity.
You can set numerous other properties on a property, including assigning a default value, a
maximum length (for strings), and whether it’s nullable. You can also assign the scope of the getter
and setter for the property (public, private, and so on), useful for, say, a property that will be
632
.
chaPter 29 The Ado.neT enTiTy FrAmeWork
mapped to a column with a calculated value in the database where you don’t want the consuming
application to attempt to set the value (by making the setter private).
The final task is to map the property to the store model. You do this as described earlier in the
chapter using the Mapping Details tool window.
Creating Complex Types
Create a complex type on the Customer entity grouping the various customer name-related properties
together in a complex type and thus making the Customer entity neater. Though you can create
a complex type from scratch, the easiest way to create a complex type is to refactor an entity by
selecting the scalar properties on the entity to be included in the complex type and having the designer
create the complex type from those properties. Follow these instructions to move the name-related
properties on the Customer entity to a complex type:
.
Select the name-related properties on the Customer entity (FirstName, LastName,
MiddleName, NameStyle, Suffix, Title) by selecting the first property, and while holding
down the Ctrl key selecting the other properties (so they are all selected at the same time).
.
Right-click one of the selected properties and select the Refactor into New Complex Type
menu item.
.
In the Model Browser will be the new complex type that it created, with its name displayed
in a textbox for you to name to something more meaningful. For this example, simply call it
CustomerName.
.
The Entity Framework designer will have created a complex type, added the selected
properties to it, removed the selected properties from the entity, and added the complex
type that it just created as a new property on the entity in their place. However, this
property will just have ComplexProperty as its name, so you will want to rename it to
something more meaningful. Select the property in the designer, press F2, and enter
Name in the textbox.
You will now find that by grouping the properties together
in this way, the entity will be easier to work with in both
the designer and in code.
Creating an entity
So far you’ve been modifying existing entities as they were
created by the Entity Data Model Wizard. However,
let’s now take a look at the process of creating an entity
from scratch and then mapping it to a table/view/stored
procedure in your storage model. Most of these aspects
have already been covered, but we’ll walk through the
required steps to get an entity configured from scratch.
You have two ways of manually creating entities.
The first is to right-click the designer surface and
select Add . Entity from the context menu. That
pops up the dialog shown in Figure 29-11, which fiGure 29-11
helps you set up the initial confi guration of the entity. When you enter a name for the entity in
the Entity Name fi eld you ’ ll notice that the Entity Set fi eld automatically updates to the plural
form of the entity name (although you can change this entity set name to something else if
required). The Base Type drop - down list enables you to select an existing entity in your entity
model that this entity will inherit from (discussed shortly). There is also a section enabling you
to specify the name and type of a property to automatically create on the entity and set as an
entity key.
The other way of creating an entity is to drag and drop the Entity component from the Toolbox
onto the designer surface. However, you ’ ll note that it doesn ’ t bring up the dialog from the
previous method, instead opting to immediately create an entity with a default name, entity set
name, and entity key property. You will then have to use the designer to modify its confi guration
to suit your needs.
The steps needed to fi nish confi guring the entity are as follows:
If required, create an inheritance relationship by specifying that t . he entity should inherit
from a base entity.
. Create the required properties on the entity, setting at least one as an entity key.
. Map these properties to the storage schema (using the Mapping Details tool window).
. Create any associations with other entities in the model.
. Validate your model to ensure that the entity is mapped correctly.
All entities must have an entity key that can be used to uniquely identify the
entity. Entity keys are conceptually the same as a primary key in a database.
As discussed earlier, you aren ’ t limited to mapping to a single database table/view per entity. This
is one of the benefi ts of building a conceptual model of the database — you may have related data
spread across a number of database tables, but through having a conceptual entity model layer in
the Entity Framework you are able to bring those different sources together into a single entity to
make working with the data a lot easier in code.
Make sure you don ’ t focus too much on the structure of the database when you
are creating your entity model — the advantage of designing a conceptual model
is that it enables you to design the model based on how you plan to use it in
code. Therefore, focus on designing your entity model, and then you can look at
how it will map to the database.
Creating an entity Model . 633
634
.
chaPter 29 The Ado.neT enTiTy FrAmeWork
creating/Modifying entity associations
You have two ways of creating an association between
two entities. The first is to right-click the header of
one of the entities and select Add . Association from
the context menu. This displays the dialog shown in
Figure 29 - 12.
This dialog includes:
.
Association Name: Give the association a
name — this will become the name of the
foreign key constraint in the database if you
update the database from the model.
.
Endpoints: These specify the entities at each
end of the association, the type of relationship
(one-to-one, one-to-many, and so on), and the
name of the navigation properties that it will
create on both entities to navigate from one
entity to the other over the association.
.
Add foreign key properties to the entity:
This enables you to create a property on the
“foreign” entity that will act as a foreign key and map to the entity key property over the
association. If you’ve already added the property that will form the foreign key on the
associated entity, you should uncheck this checkbox.
The other way to create an association is to click the Association component in the Toolbox, click
one entity to form an end on the association, and then click another entity to form the other end of
the association (if it is a one-to-many relationship, select the “one” entity first). Using this method
gives the association a default name, creates the navigation properties on both entities, and assumes
a one-to-many relationship. It will not create a foreign key property on the “foreign” entity. You can
then modify this association as required using the Properties tool window.
fiGure 29-12
Note that you cannot use the association component in a drag-and-drop fashion
from the Toolbox.
Despite having created the association, you aren’t done yet (unless you used the first method and
also selected the option to create a foreign key property for the association). Now you need to map
the property that acts as the foreign key on one entity to the entity key property on the other. The
entity whose primary key is one endpoint in the association is known, but you have to tell the Entity
Framework explicitly which property to use as the foreign key property. You can do this by selecting
the association in the designer and using the Mapping Details tool window to map the properties.
Once this is done, you may want to define a referential constraint for the association, which you can
assign by clicking the association in the designer and finding the Referential Constraint property in
the Properties tool window.
Creating an entity Model .
635
entity inheritance
In the same way that classes can inherit from other classes (a fundamental object-oriented concept),
so can entities inherit from other entities. You have a number of ways of specifying that one entity
should inherit from another, but the most straightforward method is to select an entity in the
designer, find its Base Type property in the Properties tool window, and select the entity from the
drop-down list that this entity should inherit from.
Validating an entity Model
At times your entity model may be invalid (such as when a property on an entity has not been
mapped to the storage model, or its type cannot be converted from/to the mapped column’s data
type in the database); however, despite having an invalid entity model your project will still compile.
You can run a check to see if your model is valid by right-clicking the designer surface and selecting
the Validate menu item from the context menu. This checks for any errors in your model and
displays them in the Error List tool window.
You can also set the Validate On Build property for the conceptual model to True (click an empty
space on the designer surface, and then you can find the property in the Properties tool window),
which will automatically validate the model each time you compile the project. However, again, an