Database Reference
In-Depth Information
Once we do a SaveChanges() , the inserts are all done on the database, and it's time to query our tables to see
whether we've actually inserted all of the rows correctly.
For the retrieval part, we start by getting the root entity. This is the one that has no parent. In our case, we created
a summer vacation entity, but we didn't make it the child of any other entity. This makes our summer vacation entity
the root of the hierarchy.
Now, with the root, we call another method we wrote: Print() . The Print() method takes a couple of
parameters. The first parameter is an instance of a PictureCategory . The second parameter is a level, or depth,
we are at in the hierarchy. With the root category, summer vacation, we're at the top of the hierarchy, so we pass in 0 .
The method call looks like Print(root, 0) .
In the Print() method, we write out the name of the category preceded by a space for each level deep in the
hierarchy. One of the Append() methods of the StringBuilder class takes a character and an integer. It creates an
instance of StringBuilder with the character appended the number of times specified by the integer parameter. In our
call, we send in a space and level, and it returns a string with a space for every level deep that we are in the hierarchy.
We use the ToString() method to convert the StringBuilder instance to a string.
Now for the recursive part: We iterate through the children and call the Print() method on each child, making
sure to increment the level by one. When we run out of children, we simply return. The result is the output shown
previously.
In Recipe 6-5, we show another approach to this problem using a Common Table Expression in a stored
procedure on the store side to iterate through the graph and return a single flattened result set.
2-6. Splitting an Entity Among Multiple Tables
Problem
You have two or more tables that share the same primary key, and you want to map a single entity to these two tables.
Solution
Let's illustrate the problem with the two tables shown in Figure 2-15 .
Figure 2-15. Two tables, Product and ProductWebInfo, with common primary keys
To create a model with a single entity representing these two tables, do the following:
1.
Create a new class in your project that inherits from DbContext.
2.
Create a Product POCO entity using the code in Listing 2-8.
 
Search WWH ::




Custom Search