The operation cannot be completed because the DbContext has been disposed.
I was wondering if someone help me with this issue. Here is my code:
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();
}
}
The exception occurs in this line:
contex.SaveChanges();
I can not use var for my context so what should I do?
Your using
statement will automatically dispose contex
at the end of your closing bracket }
in CResearchGrid_CellMouseDoubleClick()
I'm not exactly sure what you are saving, but to get by, you should add a using
statement and initialize your contex
object. If you do go the route of initializing your contex
in each method, you should remove it from your class member declarations. Note that you would need to modify your entities or add new entities to your contex
object for you to actually save anything. Without that, you're not really saving anything.
Another way to get going is you would initialize contex
in your constructor and implement IDisposable
. Then you can call contex.Dispose()
in the Dispose()
method.