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

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

问题描述

我有两个表 Customers Country 并使用(Entity Framework with vs 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天全站免登陆