草庐IT

c# - 解决 "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"InvalidOperationException

coder 2023-07-07 原文

我正在尝试使用 Entity Frameworkm 填充 GridView,但每次我都会收到以下错误:

"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 作为后端数据库。

我是 Entity Framework 的新手。我不明白为什么会出现此错误。谁能帮帮我?

最佳答案

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

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

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

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 实例。那是你的问题。您有 using 阻止 CosisEntities 的使用。在返回实体之前处理上下文。当一些代码稍后尝试使用延迟加载的导航属性时,它会失败,因为上下文在那个时候被释放。

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

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

这将预加载所有成员资格,并且不会使用延迟加载。详情见Loading Related Entities MSDN 上的文章。

关于c# - 解决 "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18398356/

有关c# - 解决 "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"InvalidOperationException的更多相关文章

随机推荐