[EF]SaveChanges()時若是欄位驗證錯誤將insert db失敗,如何將失敗逐筆顯示

  • 719
  • 0

[EF]SaveChanges()時若是欄位驗證錯誤將insert db失敗,如何將失敗逐筆顯示

很簡單,照下面這樣寫即可:

try
{
	using (YourDBEntities db = new YourDBEntities())
	{
		db.YourTable.Add(obj1);
		db.YourTable.Add(obj2);
		db.SaveChanges();

	}
}
catch (DbEntityValidationException dbEx)
{
	string outPutErrMsg = string.Empty;
	DbEntityValidationResult errResult =  dbEx.EntityValidationErrors.FirstOrDefault();

	foreach(DbValidationError dbValidErr in errResult.ValidationErrors)
	{
		outPutErrMsg+="PropertyName(欄位名稱):"+dbValidErr.PropertyName + ",";
		outPutErrMsg+="ErrorMessage(錯誤訊息):"+dbValidErr.ErrorMessage + ";";
		
	}
	Console.WriteLine("DbEntityValidationException occur, insert db失敗!" + outPutErrMsg);
	Console.WriteLine("Press any key to continue");
	Console.ReadKey();
	return;
}

參考資料:
[Entity Framework] 查看DbEntityValidationException發生原因
https://dotblogs.com.tw/wasichris/2015/01/24/148255