Database Reference
In-Depth Information
type BaseEntity (the base type from which our entity classes derive in this recipe). For each iteration, we make a call
to the EntityStateFactory to translate our internal TrackingState enum value to a valid EntityState value used by Entity
Framework to drive change tracking. If the client set the TrackingState to Modified , we do some additional processing.
We set the state of the entity (from Modified ) to Unchanged and call the GetDatabaseValues method on the Entry
object, which returns the current values for the entity from the underlying data store. We then assign these current
values to the OriginalValues collection in the Entry object. Under the hood, the Entity Framework change-tracking
engine detects any differences between the original and submitted values, and it marks those individual properties as
Modified and the entity as Modified . The subsequent SaveChanges operation will then only update those properties
that we changed in the client—not all of the properties in the entity.
Back in the client, we demonstrate adding, modifying, and deleting entity objects by setting the TrackingState.
The UpdateCustomer method in the service simply translates the TrackingState values to Entity Framework state
properties and submits the objects to the change-tracking engine for the correct SQL operation.
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. By
requiring each entity object to derive from a base entity type, we can expose a TrackingState value that the client can
set to communicate the needed SQL operation to the Entity Framework change-tracking engine.
In a production application, we would most likely create another layer (Visual Studio class project) to separate
the Entity Framework data access code from the Web API service. More importantly, it would not be difficult to take
the client-side tracking approach used in this recipe and implement it using generic types. Doing so would allow us to
reuse the base functionality across all of our entity types, thus reducing large amounts of redundant code.
9-5. Deleting an Entity When Disconnected
Problem
You have an object that you have retrieved from a WCF service and you want to mark it for deletion.
Solution
Suppose that you have a model like the one shown in Figure 9-5 .
Figure 9-5. A model for payments on invoices
 
Search WWH ::




Custom Search