/// <summary> /// 數據庫例外的擴展函數 /// </summary> public static class DataExceptionExtensions { /// <summary> /// 判斷例外是否由指定的唯一索引沖突引起 /// </summary> /// <param name="dataEx">例外</param> /// <param name="indexName">索引名稱</param> /// <returns></returns> public static bool IsDuplicateFor(this DataException dataEx, string indexName) { Exception ex = dataEx; while (ex.InnerException != null) { ex = ex.InnerException; } return ex.Message?.Contains(indexName) ?? false; } /// <summary> /// 判斷例外是否由外鍵依賴引起 /// </summary> /// <param name="dataEx">例外</param> /// <returns></returns> public static bool IsForgenKeyError(this DataException dataEx) { Exception ex = dataEx; while (ex.InnerException != null) { ex = ex.InnerException; } return ex.Message?.Contains("violates foreign key") ?? false; } /// <summary> /// 判斷例外是否由外鍵依賴引起並且消息包含指定字符串 /// </summary> /// <param name="dataEx">例外</param> /// <param name="messageContains">判斷是否包含的字符串</param> /// <returns></returns> public static bool IsForgenKeyError(this DataException dataEx, string messageContains) { Exception ex = dataEx; while (ex.InnerException != null) { ex = ex.InnerException; } return ((ex.Message?.Contains("violates foreign key") ?? false) && (ex.Message?.Contains(messageContains) ?? false)); } /// <summary> /// 判斷例外是否由事務沖突引起的 /// </summary> /// <param name="dataEx">例外</param> /// <returns></returns> public static bool IsConcurrentUpdate(this DataException dataEx) { Exception ex = dataEx; while (ex.InnerException != null) { ex = ex.InnerException; } return ex.Message?.Contains("concurrent update") ?? false; } }