C # Json.Net Serialize Entity with virtual properties

I am trying to serialize a complex object with virtual navigation properties. For some reason, when I try to serialize this object using WebApi (returning it from the controller) or using JsonConvert.Serialize(myObject) , all my virtual properties are zero. When I check my object, I see that they are all proxy objects. For some reason, json.net is not playing well with these proxy objects. How to get virtual properties for serialization?

+4
source share
1 answer

The problem, as mentioned in the comments, is that trying to serialize Entity Framework properties that are lazy doesn't work like that. If all proxy links have been encoded, you can serialize your entire database with a simple call.

Thus, during serialization, everything that was not explicitly loaded gets a zero value. Whenever you try to load a proxy object, a database call is made (once for each object).

You can get around this in several ways. Imagine that you have the following entity objects:

 public class Person { public int ID public string PersonName public Address PersonAddress } public class Address { public int ID public string AddressLine } 

Assuming you load your objects like this:

 Person myPerson = ObjectContext.CreateObjectSet<Person>.Where(p => p.ID == 1); 

You could do (not recommended, as this would create two separate database calls):

 Person myPerson = ObjectContext.CreateObjectSet<Person>.Where(p => p.ID == 1); var x = myPerson.Address; 

It would be best to do:

 Person myPerson = ObjectContext.CreateObjectSet<Person> .Include("PersonAddress") .Where(p => p.ID == 1); 

This avoids the associated objects being fully loaded.

Huge caution

If you try to do some kind of nested load loading (for example, you have an AddressCountry object, and you would like to get the load by changing your include as .Include("PersonAddress.AddressCountry") ), serious performance problems that may occur especially if you have large data sets.

+4
source

All Articles