Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Anyone have any experience working with ASP Web API. I'm using lazy loading and get a stack overflow error when trying to send an object. I know this is because of the infinite loop caused by lazy loading and I was wondering the best way to fix this. I know you can use data transfer objects but I was wondering if there are any better way. 

Link to post
Share on other sites

Not enough context really. However in general I don't see the value in lazy loading with Web API. In order to implement a highly responsive Web API you would separate things such that any drill down into another level of relationship occurred on another call; such as master detail for instance. You wouldn't want all of that data to be sent over the wire on the first query. That's not really considered good design when using Web API (with SPA or otherwise).

The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites
On 5/12/2016 at 11:35 AM, PleasingCone said:

Anyone have any experience working with ASP Web API. I'm using lazy loading and get a stack overflow error when trying to send an object. I know this is because of the infinite loop caused by lazy loading and I was wondering the best way to fix this. I know you can use data transfer objects but I was wondering if there are any better way. 

When you retrieve a record from the DB with EF having LazyLoading enabled it will load in the first entity to memory and references to the other related entities, then when you return that entity as a Web Api response it will then serialize it into Json or XML. I believe that the default serializer for json is Json.net. To stop Json.net from creating self referencing loops you can use the below code on your webapi config.

Aside from that you can also use the .Include() method to invoke Eager loading on an entity

More on lazyeager loading here https://msdn.microsoft.com/en-nz/data/jj574232.aspx

config.Formatters.JsonFormatter
            .SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

 

Current laptop: Macbook Air 13" Broadwell Updated - HD 6000
Current Desktop: i5 4690K (4.2GHz) | Gigabyte GTX 960 G1 (1.515 GHz) | Cooler Master V650S | HyperX 8GB 1866 MHz (1x8) | ASRock Z97 Anniversary | Samsung 1TB HDD | SanDisk Ultra II 240GB SSDZalman R1 Peripherals: Ducky Shine MX Red | Razer Naga 2012 | Razer Kraken Pro | Philips 246V 24"

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×