Jump to content

ASP API

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 comment
Share on other sites

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 comment
Share on other sites

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;

 

Link to comment
Share on other sites

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

×