Govinda Rajbhar
Govinda Rajbhar

Reputation: 3034

Unable to get navigation property(foreign key data) due to LazyLoading

I have created MVC project with WebApi. And it is working fine but I am getting problem while fetching navigation property (foreign key data) in a details method of simple controller. I came to know that the problem is due to LazyLoading written in below code, in DBEntities constructor.

public DBEntities():base("name=GJ5ServiceProviderDBEntities")       
{
    this.Configuration.LazyLoadingEnabled = false;            
}

When I remove this.Configuration.LazyLoadingEnabled = false; line from above code then it is working fine for MVC project on that time I get all navigation property (foreign key data) but after that I am getting below error for WebApi:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.

Fetching code

public async Task<ActionResult> Details(int? id)
{
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }

      TableServiceProvider tableServiceProvider = 
          await db.TableServiceProviders.FindAsync(id);

      if (tableServiceProvider == null)
      {
           return HttpNotFound();
      }
      return View(tableServiceProvider);
 }

so is there any solution to solve above both problems ?

Upvotes: 1

Views: 176

Answers (1)

Govinda Rajbhar
Govinda Rajbhar

Reputation: 3034

First of all I will like to thanks Frebin Francis to his respose and help.

I could solve above problem just adding a single line in my Code.db.Configuration.LazyLoadingEnabled = true;

This code work for me.

    public async Task<ActionResult> Details(int? id)
    {
        db.Configuration.LazyLoadingEnabled = true;
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        TableServiceProvider tableServiceProvider = await db.TableServiceProviders.FindAsync(id);
        if (tableServiceProvider == null)
        {
            return HttpNotFound();
        }
        return View(tableServiceProvider);
    }

Upvotes: 1

Related Questions