解决“ObjectContext实例已被释放,不能再用于需要连接的操作"的问题无效操作异常 [英] Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

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

问题描述

我正在尝试使用 Entity Frameworkm 填充 GridView,但每次出现以下错误时:

I am trying to populate a GridView using Entity Frameworkm but every time I am getting the following error:

"对象 'COSIS_DAL.MemberLoan' 上的属性访问器 'LoanProduct'抛出以下异常:ObjectContext 实例已被已处置,不能再用于需要连接."

"Property accessor 'LoanProduct' on object 'COSIS_DAL.MemberLoan' threw the following exception: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."

我的代码是:

public List<MemberLoan> GetAllMembersForLoan(string keyword)
{
    using (CosisEntities db = new CosisEntities())
    {
        IQueryable<MemberLoan> query = db.MemberLoans.OrderByDescending(m => m.LoanDate);
        if (!string.IsNullOrEmpty(keyword))
        {
            keyword = keyword.ToLower();
            query = query.Where(m =>
                  m.LoanProviderCode.Contains(keyword)
                  || m.MemNo.Contains(keyword)
                  || (!string.IsNullOrEmpty(m.LoanProduct.LoanProductName) && m.LoanProduct.LoanProductName.ToLower().Contains(keyword))
                  || m.Membership.MemName.Contains(keyword)
                  || m.GeneralMasterInformation.Description.Contains(keyword)

                  );
        }
        return query.ToList();
    }
}


protected void btnSearch_Click(object sender, ImageClickEventArgs e)
{
    string keyword = txtKeyword.Text.ToLower();
    LoanController c = new LoanController();
    List<COSIS_DAL.MemberLoan> list = new List<COSIS_DAL.MemberLoan>();
    list = c.GetAllMembersForLoan(keyword);

    if (list.Count <= 0)
    {
        lblMsg.Text = "No Records Found";
        GridView1.DataSourceID = null;
        GridView1.DataSource = null;
        GridView1.DataBind();
    }
    else
    {
        lblMsg.Text = "";
        GridView1.DataSourceID = null;   
        GridView1.DataSource = list;
        GridView1.DataBind();
    }
}

错误提到了 GridviewLoanProductName 列.提到:我使用 C#、ASP.net、SQL-Server 2008 作为后端数据库.

The error is mentioning the LoanProductName column of the Gridview. Mentioned: I am using C#, ASP.net, SQL-Server 2008 as back end DB.

我对实体框架很陌生.我不明白为什么我会收到这个错误.有人可以帮我吗?

I am quite new to Entity Framework. I can't understand why I am getting this error. Can anyone help me please?

推荐答案

默认情况下,Entity Framework 对导航属性使用延迟加载.这就是为什么这些属性应该被标记为虚拟的 - EF 为你的实体创建代理类并覆盖导航属性以允许延迟加载.例如.如果你有这个实体:

By default Entity Framework uses lazy-loading for navigation properties. That's why these properties should be marked as virtual - EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading. E.g. if you have this entity:

public class MemberLoan
{
   public string LoandProviderCode { get; set; }
   public virtual Membership Membership { get; set; }
}

Entity Framework 将返回从该实体继承的代理并向该代理提供 DbContext 实例,以便稍后延迟加载成员资格:

Entity Framework will return proxy inherited from this entity and provide DbContext instance to this proxy in order to allow lazy loading of membership later:

public class MemberLoanProxy : MemberLoan
{
    private CosisEntities db;
    private int membershipId;
    private Membership membership;

    public override Membership Membership 
    { 
       get 
       {
          if (membership == null)
              membership = db.Memberships.Find(membershipId);
          return membership;
       }
       set { membership = value; }
    }
}

因此,实体具有用于加载实体的 DbContext 实例.那是你的问题.您有关于 CosisEntities 用法的 using 块.在返回实体之前处理上下文.当一些代码稍后尝试使用延迟加载的导航属性时,它会失败,因为上下文在那个时刻被释放.

So, entity has instance of DbContext which was used for loading entity. That's your problem. You have using block around CosisEntities usage. Which disposes context before entities are returned. When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.

要修复此行为,您可以使用预加载导航属性,稍后您将需要此功能:

To fix this behavior you can use eager loading of navigation properties which you will need later:

IQueryable<MemberLoan> query = db.MemberLoans.Include(m => m.Membership);

这将预加载所有成员资格并且不会使用延迟加载.有关详细信息,请参阅 MSDN 上的加载相关实体文章.

That will pre-load all memberships and lazy-loading will not be used. For details see Loading Related Entities article on MSDN.

这篇关于解决“ObjectContext实例已被释放,不能再用于需要连接的操作"的问题无效操作异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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