Database Reference
In-Depth Information
Back in the client, we execute our next operation, changing the quantity of order and sending the entity back to
the Web API service by calling the
PutAsJsonAsync
method from the
HttpClient
object. If you place a breakpoint in
the
Put
Action Method in the Order Web API controller class, you'll see that it receives the order object as a parameter
in the service. From the context object, we invoke the
Entry
method, passing in the Order entity reference. Then,
by setting the
State
property to
Modified
attaches the entity of the underlying context object. The subsequent call
to
SaveChanges
generates a SQL Update statement. In this case, we update all columns for order. In later recipes,
we'll see how we can update only those properties that have changed. We complete the operation by sending an
HttpResponseMethod
to caller with a HTTP status code of
200
.
Back in the client, we invoke our final operation, which will delete the Order entity from the underlying data
store. We append the Id for the order as an additional URI segment and call the Web API service with the
DeleteAsync
method from the
HttpClient
object. In the service, we retrieve the target order from the data store and pass its
reference to the
Remove
method, called from the Order entity and context object. Doing so marks the entity as deleted.
The subsequent call to
SaveChanges
generates a SQL Delete statement that removes the order from the underlying
data store.
In this recipe, we've seen that we can encapsulate Entity Framework data operations behind a Web API service.
The client can consume the service by using the HttpClient object that is exposed by the Web API client API. Adhering
to the Web API's HTTP verb-based dispatch, we leverage the
Post
action method to add a new record, the
Put
action
method to update a record, and the
Delete
action method to remove a record. Also in the recipe, we implement Entity
Framework using the code-first approach.
In a production application, we would most likely create a separate layer (Visual Studio class project) to separate
the Entity Framework data access code from the Web API service.
9-2. Updating Disconnected Entities with WCF
Problem
You want to use a Windows Communication Foundation (WCF) service to expose selects, inserts, deletes, and updates
for a data store and keep the database operations as simple as possible. Additionally, you want to implement the
code-first approach for Entity Framework 6 to manage data access.
Solution
Let's say that you have a model like the one shown in Figure
9-2
.
Figure 9-2.
A model for blog posts and comments