ObjectContext 实例已被释放,不能再用于需要连接的操作.在参考表中 [英] The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. in Reference table

查看:17
本文介绍了ObjectContext 实例已被释放,不能再用于需要连接的操作.在参考表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表 CustomersCountry 并使用(实体框架与 2012 年)

I have two tables Customers and Country and use ( Entity Framework with vs 2012 )

和模型类

 using System;
 using System.Collections.Generic;

 public partial class Customer
 {
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string Address { get; set; }
     public string Email { get; set; }
     public string Phone { get; set; }
     public Nullable<int> CountrryId { get; set; }
     public string Note { get; set; }

     public virtual Country Country { get; set; }
 }

我尝试构建一个选择查询以获取所有具有国家/地区名称的客户.但我总是收到以下错误消息.

I try to build a select query for get all customers with Country Name. But I always get the below error message.

推荐答案

您正尝试在处理数据上下文后访问关联属性 Country.实体框架,默认情况下,加载关联属性懒洋洋的.换句话说,当您第一次尝试访问关联属性时,它会再次访问数据库.为了进行数据库访问,实体框架必须使用数据上下文.在您的情况下,它会尝试使用由 jQGridDemoEntities db = new jQGridDemoEntities() 创建的数据上下文,不幸的是,该数据上下文此时已在您的代码中处理.由于您已退出使用块,因此数据上下文已被处理.

You are trying to access an association property Country after the data context has been disposed. Entity Framework, by default, loads association properties lazily. In other words, it makes another trip to the database when you try to access the association property for the first time. To make this trip to the database, Entity Framework must use a data context. In your case, it would be trying to use the data context created by jQGridDemoEntities db = new jQGridDemoEntities() which has unfortunately been disposed at this point in your code. The data context has been disposed because you've exited the using block.

您有三个选择来解决这个问题:

You have three options to get around this problem:

  • 当数据上下文仍然存在时访问关联属性.更具体地说,将访问关联属性的代码移动到 using 块中

  • Access the association property when the data context is still alive. More concretely, move your code where you access the association property into your using block

按照我指定的第一个链接中的说明快速加载关联属性

Eagerly load the association property as explained in the first link I specified

customers = db.Customers.Include(c => c.Country).ToList()

在数据上下文仍然存在的情况下,明确选择要从数据库返回的内容.并使用该信息构建返回的 json 对象.

Explicitly select what you want to return from the database while the data context is still alive. And use that information to construct the json object your return.

customers = db.Customers.Select(c => new
{
    c.Id,
    c.FirstName,
    c.LastName,
    c.Address,
    c.Email,
    c.Phone,
    CountryName = c.Country.Name,
    c.Note
};

这篇关于ObjectContext 实例已被释放,不能再用于需要连接的操作.在参考表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆