由于延迟加载,无法获取导航 属性(外键数据)

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

我已经使用 WebApi 创建了 MVC 项目。它工作正常,但在简单控制器的详细信息方法中获取 导航 属性(外键数据) 时出现问题。我开始知道问题是由于 LazyLoading 写在下面的代码中,在 DBEntities 构造函数中。

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

当我从上面的代码中删除 this.Configuration.LazyLoadingEnabled = false; 行时,它在那个时候对 MVC 项目工作正常我得到了所有 导航 属性 (外键数据) 但在那之后我遇到了 WebApi 的以下错误:

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

正在获取代码

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);
 }

那么有没有办法解决以上两个问题呢?

首先我要感谢Frebin Francis他的回复和帮助。

我只需在我的代码中添加一行即可解决上述问题。db.Configuration.LazyLoadingEnabled = true;

这段代码对我有用。

    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);
    }