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

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

问题描述

我有两个表的客户国家并使用(实体框架在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.

请帮助。

推荐答案

您试图访问一个关联属性国家后的数据上下文已被释放。实体框架,默认情况下,负载关联属性的懒洋洋。换句话说,它使再次访问数据库时您尝试访问关联属性的第一次。为了让此行到数据库中,实体框架必须使用数据上下文。你的情况,它会试图使用由 jQGridDemoEntities DB =新jQGridDemoEntities创建的数据上下文()已不幸被布置在您的code这一点。数据上下文已被释放,因为你已经使用块退出

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:


  • 在数据方面仍然活着访问关联关系的性质。更具体地说,在那里你访问关联属性到您使用的块移动你的code

  • 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

客户= db.Customers.Include(C =&GT; 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中实例已设置,不能再被用于需要连接的操作。在Referece表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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