视图中出错:ObjectContext已被释放

时间:2015-05-22 16:50:03

标签: c# asp.net asp.net-mvc

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

在我的应用程序中呈现视图时,我收到此错误。我已经查看了类似问题的各种SO答案,并且无法解决我的问题。 这是我的班级:

public class categoryList
{
    public static Dictionary<string, string> getCategories()
    {
        Dictionary<string, string> myList = new Dictionary<string, string>();
        using (ProductContext context = new ProductContext())
        {
            List<CategoryModel> list = 
                 (from c in context.Categories select c)
                .ToList<CategoryModel>();

            myList = list
              .GroupBy(c => c.category, StringComparer.OrdinalIgnoreCase)
              .ToDictionary(g => g.Key, g => g.First().category, StringComparer.OrdinalIgnoreCase);
            return myList;
        }

    }
}

然后这是我的视图代码调用:

<div class="form-group">
                @Html.LabelFor(model => model.Category, "Category", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.Category.category, newBestPlay.Models.ProductModel.getCategories(), new { @class = "form-control"})
                    @Html.ValidationMessageFor(model => model.Category)
                </div>
            </div>

编辑:为了帮助别人弄清楚我的问题,我粘贴了整个ProductModel类:

public class ProductModel
{
    public int ID { get; set; }

    [Display(Name = "Item #")]
    public int itemNumber { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Product")]
    [MaxLength(50)]
    public String product { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Description")]
    [MaxLength(500)]
    public String description { get; set; }

    [DefaultValue(true)]
    [Display(Name = "Active?")]
    public bool active { get; set; }

    [Display(Name = "Image Name")]
    public String imageName { get; set; }

    [Display(Name = "PDF Name")]
    public String PDFName { get; set; }

    [ForeignKey("Category")]
    public virtual int CategoryID { get; set; }

    public virtual CategoryModel Category { get; set; }

    public IEnumerable<SelectListItem> CategoryList { get; set; }

    public static SelectList getCategories()
    {
        Dictionary<string, string> requestList = newBestPlay.Models.categoryList.getCategories();

        return new SelectList(requestList, "Key", "Value");
    }


}

这是CategoryModel:

public class CategoryModel
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Category")]
    [MaxLength(50)]
    public String category { get; set; }

    [DefaultValue(true)]
    [Display(Name = "Active?")]
    public bool active { get; set; }
}

1 个答案:

答案 0 :(得分:2)

当您的上下文配置为使用LazyLoading时,将抛出此异常。如果启用延迟加载,EF将仅检索您在select子句中指定的对象。

  1. 如果“CategoryModel”类包含嵌套对象,并且您正在使用延迟加载,则不会从数据库中检索这些对象。
  2. 由于您将select包含在using块中,因此在放置控制器之后,连接以及上下文已经处理完毕。
  3. 如果要在视图中引用其中一个内部类对象,例如“Model.InnerClass.Property”,则会出现此异常。
  4. 如果之前的陈述属实,您可以尝试以下方法:

    public class categoryList
    {
       public static Dictionary<string, string> getCategories()
       {
           Dictionary<string, string> myList = new Dictionary<string, string>();
           using (ProductContext context = new ProductContext())
           {
               List<CategoryModel> list = 
                       (from c in context.Categories.Include("PropertyName") select c)
                       .ToList<CategoryModel>();
    
               myList = list
               .GroupBy(c => c.category, StringComparer.OrdinalIgnoreCase)
               .ToDictionary(g => g.Key, g => g.First().category, StringComparer.OrdinalIgnoreCase);
               return myList;
           }
        }
    }
    

    如果内部对象包含其他对象,则应在include中指定该对象,因此EF在处置上下文之前检索该信息:

    .Include("InnerProperty.NestedProperty") 
    

    我希望它有所帮助

    -----编辑1 -----------

    以下是代码示例:

    public class ProductModel
    {
       public virtual CategoryModel Category { get; set; }
    }
    
    public class CategoryModel 
    {
       public virtual UserAddress Address {get; set;}
    }
    
    public class UserAddress
    {
       public string Street1 {get; set;}
    }
    

    假设以前的型号,Include将如下:

    List<CategoryModel> list = (from c in context.Categories
                                                 .Include("Category") 
                                                 .Include("Category.Address") 
                                select c)
                               .ToList<CategoryModel>();