另一種選擇是簡單地不使用EF來進行刪除操作。
如果您執行原始SQL DELETE TableName WHERE PrimaryKey = @Key
並且記錄已被刪除,那麼您將不會收到錯誤。
小巧玲瓏
using (var sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
{
sqlConnection.Open();
string sqlQuery = "DELETE FROM [dbo].[Customer] WHERE [email protected]";
sqlConnection.Execute(sqlQuery, new {customerId});
sqlConnection.Close();
}
托爾鏈
dataSource.DeleteByKey ("Customer", CustomerId).Execute();
EF
using (var context = new [...]) {
context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[Customer] WHERE [email protected]", new SqlParameter("@CustomerId", CustomerId));
}
(是的,使用EF執行非EF查詢是浪費的,但它是一個選項。)
事務允許執行一個數據庫狀態的多個語句。實體框架支持事務。 –
我認爲更好的辦法是在點擊時禁用「刪除」按鈕。 – Smartkid
@Smartkid謝謝。有沒有想過這樣一個簡單的解決方案 – dnanon