Database Reference
In-Depth Information
If you are not familiar with this pattern, it's really pretty simple. Normally, when we get a new instance of an
object, we use the new operator and assign the result to some variable. When the variable goes out of scope and the
object is no longer referenced by anything else, the garbage collector will do its job at some point and reclaim the
memory for the object. That works great for most of the objects that we create in our .NET applications because most
objects hold on to resources that can wait around for whenever the garbage collector has a chance to reclaim them.
The garbage collector is rather nondeterministic. It reclaims resources pretty much on its own schedule, which we can
only partially influence.
Instances of DbContext hold on to system resources such as database connections that we want to release as
soon as we're done with them. We don't really want these database connections to stay open waiting for the garbage
collector eventually to reclaim them.
There are a few nice features of using() statements. First, when the code execution leaves the using() {} block,
the Dispose() method on the context will be called because DbContext implements the IDisposable interface. For
DbContext, the Dispose() method closes any active database connections and properly cleans up any other resources
that need to be released.
Second, no matter how the code leaves the using(){} block, the Dispose() method is called. Most importantly,
this includes return statements and exceptions that may be thrown within the code block. The using(){} block is kind
of a guarantee that critical resources will be reclaimed properly.
The best practice here is always to wrap your code in the using(){} block when creating new instances of
DbContext. It's one more step to help bulletproof your code.
2-2. Creating a Model from an Existing Database
Problem
You have an existing database with tables, perhaps a few views, and some foreign key constraints, and you want to
create a model for this database.
Solution
Let's say that you have database describing poets and their poetry. Your relational database might look something like
the diagram in Figure 2-7 .
Figure 2-7. A simple database for poets and their poetry
From this database diagram, you can see that a poet can be the author of one or more poems, and each poem
can be categorized by its meter, which is the basic pattern of a poem's verse. It's not shown in this diagram, but our
database also has a view that joins the tables together so that we can more easily enumerate each poet and poem,
as well as the poem's meter.
 
Search WWH ::




Custom Search