Search code examples
.netwcfentity-frameworkdto

How to create and detect changes in sparse DTOs?


I'm developing some WCF services that are backed by a DAL that leverages the Entity Framework. The clients, services and the DAL communicate with one another via Data Transport Objects (DTOs) in the form of WCF Data Contracts. (The Entity objects from EF are encapsulated within the DAL).

To minimize the amount of data over the wire, I want to support the transmission of sparse DTOs--a subset of the total fields in the objects.

For example, say I have a DTO like this:

public class widget
{
   public string ID { get; set; }
   public string Name { get; set: }
   public int Amount { get; set; }
   public string Color { get; set; }
}

Say the original state of the object is:

ID = "xxx"
Name = "flux capacitor"
Amount = 42
Color = "purple"

Now, the client may want to display a list of all of the widgets in the system, so requests a list of all widgets from the service, but requests only the ID and Name fields.

First question: How can I send a sparse DTO to the client in this case? I know that DataMembers can be optional in DataContracts, but I'm not sure what the code looks like to initialize that. Just fill in the requested fields?

Now say the Name field in the UI is editable and a user changes the xxx widget's name. The client triggers an update from the service sending along:

ID = "xxx"
Name = "a new name"

At this point, I want to be able to detect that only the Name field has changed and trigger the update on the Entity within the DAL. The next question is: how can I tell that the client sent a DTO where only the ID and Name fields were specified?


Solution

  • What I have decided to do is create the DTOs with nullable types for all primitive fields. That way, when a DTO comes in from a client request, the code can check for NULL. If NULL, the field was not specified by the client. Otherwise, grab the value and set it on the Entity instance from EF and let the database context figure out what has changed...