Database Reference
In-Depth Information
To query our model and, of course, verify that we did indeed save everything to the database, we grab a fresh
instance of the object context and query it using LINQ to Entities. We could have reused the same instance of the
database context, but then we know it has the object graph and any subsequent queries we run against it won't flow
through to the database because the graph is already in memory.
Using LINQ to Entities, we query for all of the poets, and for each poet we print out the poet's name and the
details for each of their poems. The code is pretty simple, but it does use a couple of nested for loops.
The last block of code uses the vwLibrary entity. This entity is based on our vwLibrary view. This view joins the
tables together to flatten things out a bit and provide a cleaner perspective. When we query for each poet against the
vwLibraries entity set, we can get by with just one for loop. The output is a little different because we repeat the poet's
name for each poem.
There is one last thing to note in this example. We didn't insert the poets, poems, and meters using the vwLibrary
entity because views are always read-only in most database systems. In Entity Framework, we can't insert (or update,
or delete) entities that are based on views. Of course, we'll show you exactly how to overcome this little challenge in
many of the recipes in this topic!
2-3. Modeling a Many-to-Many Relationship with No Payload
Problem
You have a couple of tables in an existing database that are related to each other via a link or junction table. The link
table contains just the foreign keys used to link the two tables together into a many-to-many relationship. You want
to import these tables to model this many-to-many relationship.
Solution
Let's say that your database tables look something like the database diagram in Figure 2-10 .
Figure 2-10. Artists and albums in a many-to-many relationship
To create a model and import these tables and relationships, 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# Items 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 Album, LinkTable,
and Artist. Leave the Pluralize and Foreign Key options checked. Click Finish.
The wizard will create the model shown in Figure 2-11 .
 
Search WWH ::




Custom Search