Returning Only a Subset of Members

Often you’ll need to return only a subset of the properties of a class; this exercise shows how to do that. Take the case of the Employeeclass shown here-

The Employee Class with Five Properties
public class Employee
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public decimal Compensation { get; set; }
     public int Department { get; set; }

public HttpResponseMessage Get()
     var values = list.Select(e => new
                              Identifier = e.Id, 
                              Name = e.FirstName + ” ” + e.LastName 
     var response = new HttpResponseMessage(HttpStatusCode.OK)
                              Content = new ObjectContent(values.GetType(),
     return response;

This code explicitly returns ObjectContent from the Getaction method, using the anonymous type that we create in the select clause. The important point to note here is that XmlFormattercannot handle anonymous types. 
We pass the JsonFormatterwhile creating the ObjectContentinstance and make sure conneg result is not used and any formatter other than JsonFormatteris not picked for serialization. Here is the JSON output:
          “Identifier”: 12345,
          “Name”: “John Human”
          “Identifier”: 12346,
          “Name”: “Jane Public”
          “Identifier”: 12347,
          “Name”: “Joseph Law”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s