Serialize Entity Framework Objects Without Lazy Loading

asp.netentity-frameworkjsonreflectionserialization

I have a very specific scenario that I'm not sure is possible to fully support:

I have an ASP.NET application that uses Entity Framework 6.3 for it's data management.

I also have a generic audit library that I use to log when specific types of data are viewed. This library is designed to be ignorant of the data/objects it logs. I would like to log entity framework created objects in json serialized format.

The issue I am running into is when I attempt to serialize Entity Framework objects with virtual references. The serialization process will trigger a lazy load on all virtual properties.

There are a few solutions that will stop this:

  1. Disable Lazy Loading for an EF Context:

    public SomeContext()
    {
    this.Configuration.LazyLoadingEnabled = false;
    }

  2. Create a DTO from the Entity Framework Object and serialize that instead.

  3. Project the data into a new type when reading from the context.

Unfortunately, options 1 and 3 are off the table. I can't go back and modify the context to satisfy the needs of the logger for various reasons, one of which is that I am not the "owner" of the projects I'm modifying. Same goes for changing the data types returned.

Basically I am trying to enter logs without impacting the functionality of the application whatsoever.

That leaves option 2. I could create a temporary DTO, log that, and then dispose of it. The problem with this approach is that whoever is adding the log references would need an understanding of the objects to create a DTO. I guess I could use something like Automapper to assist with this, but again, it's definitely a lot more work just to get around the fact that we cannot simply serialize the EF object.

My question is, is there an option 4? Is there a way to serialize an EF object without triggering the lazy loading while also not impacting the way the application current works?

Perhaps I could do some reflection into the EF object and do either copy the object or more directly direct the serialization.

Best Answer

Here is my suggestion.

Create another partial class for one of your Entity classes. Include in your partial class a Serialize() method that only serializes the fields that you want, and excludes those fields that are lazy loaded.

When you've figured out how to do that reliably, either write by hand new partial classes for each of the remaining Entity classes, or create a T4 class that generates those classes for you.