通常我們碰到 EF 的問題時都會以下這樣的情形,真的是很難處理 要處理這些問題,要嘛就是多處理幾次,就會知道問題點在哪裡,不然就是裝些輔助工具把 EF 的訊息拉出來查看,現在有這個DbEntityValidationException類別可以快速取出想要得知的訊息。 使用方式直接替換Exception就好,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
try { var objectContext = ((IObjectContextAdapter)this).ObjectContext;
publicpartialclassSomethingSomethingEntities { publicoverrideintSaveChanges() { try { returnbase.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, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. thrownew DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } } }