Database Reference
In-Depth Information
Now that the completed object graph is part of the database context, the only thing left to do is to use
SaveChanges() to save the whole thing to the database.
When we query the database in a brand-new Database Context, we grab the artists and display their albums.
Then we grab the albums and print the artists that created the albums.
Notice that we never refer to the underlying LinkTable from Figure 2-10 . In fact, this table is not even represented
in our model as an entity. The LinkTable is represented in the many-to-many association, which we access via the
Artists and Albums navigation properties.
2-4. Modeling a Many-to-Many Relationship with a Payload
Problem
You have a many-to-many relationship in which the link table contains some payload data (any additional columns
beyond the foreign keys), and you want to create a model that represents the many-to-many relationship as two
one-to-many associations.
Solution
Entity Framework does not support associations with properties, so creating a model like the one in the previous
recipe won't work. As we saw in the previous recipe, if the link table in a many-to-many relationship contains just the
foreign keys for the relationship, Entity Framework will surface the link table as an association and not as an entity
type. If the link table contains additional information, Entity Framework will create a separate entity type to represent
the link table. The resulting model will contain two one-to-many associations with an entity type representing the
underlying link table.
Suppose we have the tables and relationships shown in Figure 2-12 .
Figure 2-12. A many-to-many relationship with payload
An Order can have many Items. An Item can be on many Orders. Additionally, we have a Count property
connected to each instance of the Order, Item relationship. This Count property is referred to as a payload .
To create a model and import these tables and relationships into the model, do the following:
1.
Add a new model to your project by right-clicking your project and selecting
Add New Item. Choose ADO.NET Entity Data Model from the Visual C# Data templates.
2.
Select Generate from database. Click Next.
3.
Use the wizard to select an existing connection to your database or create a new
connection.
4.
From the Choose Your Database Object dialog box, select the tables Order, OrderItem,
and Item. Leave the Pluralize and Foreign Key options checked. Click Finish.
The wizard will create the model in Figure 2-13 .
 
Search WWH ::




Custom Search