我有,我用我的EF上下文從數據庫將數據加載到一個DataGridView,以使用戶能夠做出一些改變一個用戶控件:用戶控件和EF上下文處理
public partial class MyUserControl: UserControl
{
MyEntities context;
public ViewMasterData()
{
InitializeComponent();
createComboBoxTable();
}
private void MyUserControl_Load(object sender, EventArgs e)
{
context = new MyEntities();
}
// Other methods to fill the dataGridView and Save the data back to the DB
private void SaveChanges()
{
context.SaveChanges();
}
}
我想當我離開UserControl時(即導航到另一個UserControl)處理上下文,但似乎在UserControl的Dispose方法(在代碼生成的)上調用context.Dispose()不起作用,因爲它僅在我關閉了整個WinForm。我無法使用「使用」,因爲我需要保持上下文打開才能執行更改並保存。
問題是:當我離開UserControl時,如何正確地處理上下文? 感謝!
感謝您的反饋。我需要在DataGridView中對多個記錄進行更改,然後在最後單擊Save。我如何用你提出的方法來實現這一點?如何讓EntityState.Modified用戶更改/添加的所有recoreds? – andrew0007 2014-12-02 15:01:01
很高興幫助,看到我更新的答案。 – Fredrik 2014-12-03 09:35:53