Entity Framework + Web API, return Entities (Complex, collections, etc) outside DbContext

264 views Asked by At

Here is my situation. I use Entity Framework 4 with the Web API

The structure of my code is quite simple, I have the Service layer where all my rest API is organized, I have my Business logic layer where I have business controllers to manage Transactions between the rest calls and the data layer. Finally, I have a data layer with generic repositories and a DAO to access the whole thing.

In my Business controllers, I use using to inject a non transactionnal (read only methods) OR a transactional (CRUD methods) DbContext.

When returning values to my REST API, I parse it into JSON.

The problem is that I keep having this exception: Newtonsoft.Json.JsonSerializationException

I return my entities / collections / lists outside of my using{} statement, which I think EF does not like by default.

In debug mode, sometimes, I will manage to retrieve all data, but not all the time. Since my entities come from a query within a DbContext, I think that the behavior is to remove loaded sub-properties after the context has been disposed of.

Fact is, I want to keep my structure as is, and I was wondering the following:

Is there a way of returning complete (not lazy-loaded) entities after leaving the using{} statement?

Thanks a lot

1

There are 1 answers

0
Jean-michel Benoit On BEST ANSWER

I actually read more about Entity Frameworks behavior. What I get is actually standard for EF. I have to force the context to Load() my refered entities in order to get them after leaving the context.