2018年5月8日 星期二

改善 SaveChanges() exception 顯示的錯誤訊息

擴充 .Context.cs 覆寫 SaveChanges() 顯示詳細的驗證錯誤訊息

1. 在Models資料夾底下新增資料夾,建議取名Extend
2. 新增class,檔名取相同名稱方便識別,如 Model1.Context.cs
3. 檔案範例內容如下
namespace xxx.Models
{
public partial class xxxEntities
    {
        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, "驗證錯誤訊息: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }
    }
}

參考來源

沒有留言:

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...