0
我無法確定爲什麼下面的代碼失敗的FormClosing事件期間將更改保存到數據庫:保存更改的FormClosing在數據庫失敗
private void frmClient_FormClosing(object sender, FormClosingEventArgs e)
{
if (bAreChanges)
{
DialogResult dialogResult = MessageBox.Show("Do you wish to save the changes to the database?",
"Confirmation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
using (var context = new SomeEntities()) {
var value = "abc";
context.sometable.Add(new sometable() {somefield = value});
context.SaveChanges();
//the same exact code works when executed from a simple button click that is placed on this form.
}
this.Validate(); // even added this line as suggested in another Stackoverflow question
}
else if (dialogResult == DialogResult.No)
{
}
else
{
e.Cancel = true;
}
}
}
可能的SaveChanges的某些部分()是異步的,因此表單處置數據庫操作執行之前?
編輯:這是一個子窗體,而不是主窗體 - 應用程序在此窗體關閉後繼續運行。如果這是某種相關性。
您是否將調試器附加到代碼並逐行執行?這是找出實際情況的第一步。 – mason
剛剛完成,它完全按照它的樣子,但數據庫中沒有任何更改。從一個按鈕執行而不是在FormClosing事件中時,相同的確切代碼有效。 – astralmaster
如果在'using'部分之前放置'e.Cancel = true;'會發生什麼?它保存更改嗎? – MatSnow