The three classes we created earlier contain all of the code
necessary to implement our model and data persistence for NerdDinner.
Let’s now look at a few code examples of how we can use these classes to
perform common data scenarios:
Query Using LINQ Expressions
We can write LINQ query expressions to retrieve data from a
database using the following code. Below we are using a LINQ expression
to retrieve all dinners that occur in the future:
We can also take advantage of relationships between Dinners
and RSVPs when writing our LINQ expressions. Notice below how our “where”
statement filters by dinners whose RSVP count is greater than 0:
Note that the “where” filter in the above query (where we
are retrieving only those Dinners who have at least one RSVP) executes in the
database server – making the query and the amount of data we retrieve very
efficient.
Retrieving a Single Instance
We can use LINQ’s Single() method with a lambda query to
retrieve a single instance of a Dinner using code like below:
Alternatively, we can also take advantage of a Find() method
that EF “code-first” exposes that allows you to easily retrieve an instance
based on its ID:
Adding a new Dinner
The code below demonstrates how to create and add a new
Dinner to the database. All we need to do is to “new” a Dinner object,
set properties on it, and then add it to the Dinners property of our
NerdDinners context object. The NerdDinner context class supports a “unit
of work” pattern that enables you to add multiple models to the context, and
then call “SaveChanges()” on it to persist all of the changes to a database as
a single atomic transaction.
Updating a Dinner
The code below demonstrates how to retrieve a Dinner, update
one of its properties, and then save the changes back to the database: