【问题标题】:The operation cannot be completed because the DbContext has been disposed. Affect running program操作无法完成,因为 DbContext 已被释放。影响运行程序
【发布时间】:2017-05-11 20:48:34
【问题描述】:

操作无法完成,因为 DbContext 已被释放。

我想知道是否有人帮助我解决这个问题。这是我的代码:

public partial class CustomerResearchForm : MetroFramework.Forms.MetroForm
{
    FactorEntities contex;
    public CustomerResearchForm()
    {
        InitializeComponent();
    }

    private void CustomerResearchForm_Load(object sender, EventArgs e)
    {
    }

    private void CResearchGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        CustomerUpdateAndDelete CustomerUpdateAndDelete = new CustomerUpdateAndDelete();
        using (  contex =new FactorEntities())
        {       
            var sendergrid=(DataGridView)sender;
            int customercode = Convert.ToInt32(sendergrid.Rows[e.RowIndex].Cells[1].Value);
            var customer = from _customer in contex.tblCustomers where
               _customer.CustomerCode==customercode select _customer;

            CustomerUpdateAndDelete.tblCustomerBindingSource.DataSource = customer.ToList();
            CustomerUpdateAndDelete.Show();
            CustomerUpdateAndDelete.tblCustomerBindingNavigatorSaveItem.Click+=tblCustomerBindingNavigatorSaveItem_Click;
        }
    }

    private void tblCustomerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        contex.SaveChanges();    
        throw new NotImplementedException();
    }
}

异常发生在这一行:

contex.SaveChanges();

我不能将 var 用于我的上下文,我该怎么办?

【问题讨论】:

  • 您的上下文包含在一个 using 中,您知道 using() {} 中的对象会自动分配,不是吗?
  • 做一个C# google search on the key word SCOPE
  • 亲爱的@MethodMan 我明白了。我从我的代码中消除了它,错误消失了。但是在我编辑 contex info 之后,它仍然没有更新我的数据库! :(

标签: c# entity-framework objectdisposedexception


【解决方案1】:

您的using 语句将自动在CResearchGrid_CellMouseDoubleClick() 中的右括号} 末尾处理contex

我不完全确定您要保存什么,但为了解决问题,您应该添加一个 using 语句并初始化您的 contex 对象。如果你确实在每个方法中初始化你的contex,你应该从你的类成员声明中删除它。请注意,您需要修改实体或将新实体添加到 contex 对象,以便实际保存任何内容。没有它,你并没有真正节省任何东西。

另一种方法是在构造函数中初始化contex 并实现IDisposable。然后就可以在Dispose()方法中调用contex.Dispose()了。

【讨论】:

  • @MethodMan 你说得对。我想调用我的 BindingNavigatorSaveItem 并在其事件中编写我的代码,所以我需要另一种方法,例如( tblCustomerBindingNavigatorSaveItem_Click ),我应该考虑一种在循环中使用我的上下文的方法。
猜你喜欢
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2015-04-03
  • 2015-08-09
  • 1970-01-01
相关资源
最近更新 更多