“ ObjectContext实例已被处置”-即使使用了using(context)语句和ToList()

问题描述 投票:2回答:1

我有一个首先使用EF代码运行的MVC3项目。

这是我的家庭/索引代码:

public ActionResult Index()
{
    var IndVM = new IndexVM();
    using (QuoteContext QDomain = new QuoteContext())
    {
        IndVM.Quotes = QDomain.Quotes.Include("Tags").Include("Author").OrderByDescending(x => x.CreatedOn).Take(5).ToList();
        IndVM.Tags = QDomain.Tags.OrderByDescending(x => x.Quotes.Count).ToList();
        IndVM.Authors = QDomain.Authors.OrderByDescending(x => x.Quotes.Count).Take(5).ToList();
    }
    return View(IndVM);
}

您可以看到,我在using语句中包含了Querying内容,并且我也调用了ToList(),但仍然出现错误:

ObjectContext实例已被处置,不能再用于需要连接的操作。

这是EF Code First中的错误吗?

asp.net-mvc-3 entity-framework c#-4.0 ef-code-first
1个回答
1
投票

您必须关闭延迟加载,否则序列化程序将尝试遍历导航属性并引发此异常。

public ActionResult Index()
{
    var IndVM = new IndexVM();
    using (QuoteContext QDomain = new QuoteContext())
    {
        QDomain.ContextOptions.LazyLoadingEnabled = false;
        // Query and populate IndVM here...
    }
    return View(IndVM);
}
© www.soinside.com 2019 - 2024. All rights reserved.