I am creating my first ASP.NET MVC4 Web API. I have a database with 20 or so entities already created and hosted on Azure, and used Entity Framework to reverse engineer the database into POCO classes.
They ended up looking something like this:
public class Activity
{
public Activity()
{
this.ActivityCategories = new List<ActivityCategory>();
this.ActivityImages = new List<ActivityImage>();
this.PerformedActivities = new List<PerformedActivity>();
this.UserActivities = new List<UserActivity>();
}
public int ActivityID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> Thumbnail { get; set; }
public virtual Image Image { get; set; }
public virtual ICollection<ActivityCategory> ActivityCategories { get; set; }
public virtual ICollection<ActivityImage> ActivityImages { get; set; }
public virtual ICollection<PerformedActivity> PerformedActivities { get; set; }
public virtual ICollection<UserActivity> UserActivities { get; set; }
}
Then, I created an ApiController extension class with an action like so:
public IEnumerable<Activity> All()
{
return db.Activities.ToArray();
}
And, as expected, it returned a very long JSON reply. The JSON reply included everything defined in the Activity class. But what if I don't want to include EVERYTHING? For instance, I don't want to return things like UserActivities, PerformedActivities, etc.
Basically I want my JSON to look something like:
[
{
"id":"32",
"name":"this activity name",
"description":"blah blah",
"thumbnail":"http://mydomain.com/images/32/thumbnail.png",
"images": [
{
"name":"this image",
"url":"http://mydomain.com/images/32/1.png",
},
{
"name":"cool image",
"url":"http://mydomain.com/images/32/2.png",
},
],
},
...
]
(ignore any formatting errors in my JSON, just typed up the example really fast)
Notice, I don't want to necessarily use the same property names either. Is there an efficient way to massage my data into the format I want?
My first thought is to copy each activity into an array of structs that only include the properties I want. Is there a more elegant solution?