I am using EF 5, and ASP.NET Web API to return JSON from my controllers. My example is for a pet service. For this question the entities are Client, Pet, and Veterinarian. The relationships are:
Client => one-to-many => Pet => one-to-one => Veterinarian
and, reversing the hierarchy:
Veterinarian => one-to-many => Pet => one-to-one => Client
In my PetsController, the GetPets action looks like this:
var pets= db.Pets
.Where(p => p.IsActive == true)
.Include(p => p.Client)
.Include(p => p.Veterinarian);
return Mapper.Map<IEnumerable<Pet>, IEnumerable<PetDTO>>(pets); // Using Automapper to map to a DTO
The resulting JSON has Pets, for each Pet a Client, for each Pet a Veterinarian AND for each Veterinarian, a collection of Pets.
I understand why the collection of pets is showing up in the JSON, but it's not relevant (at least not now) to my list of Pets from the controller action. I'm looking for an elegant way to remove the collection of pets. Right now I'm using what feels like a hack:
var pets= db.Pets
.Where(p => p.IsActive == true)
.Include(p => p.Client)
.Include(p => p.Veterinarian);
foreach (Pet pet in pets) {
pet.Veterinarian.Pets = null; // Remove the Pets collection before serializing
}
return Mapper.Map<IEnumerable<Pet>, IEnumerable<PetDTO>>(pets); // Using Automapper to map
I've tried some things with the serializer and with some IQuerable methods (many of which I am not familiar) but to no avail.