为何SaveChangesAsync执行失败时抛出异常而非返回0?
if (await context.SaveChangesAsync() > 0) in EF6? Great question! It’s totally reasonable to wonder about this pattern, especially since EF6 explicitly throws a DbUpdateException when a save operation fails (instead of returning 0). Let’s break down the main reasons you’ll still see this check used:
To differentiate "no changes to save" from a successful write
The most valid use case here is verifying whether the save actually resulted in database changes. If you callSaveChangesAsync()when no entities have been added, modified, or deleted, it will legitimately return 0 without throwing exceptions. This check lets you handle scenarios where you need to confirm a write happened—like logging that a change was persisted, or updating a UI to show a "success" message only when something actually changed.Habit carried over from other code or frameworks
Some developers bring this pattern from older synchronousSaveChanges()code (where the same return value behavior applies) or from other ORMs/data access tools where a 0 return might indicate a failure. It’s easy to replicate the check when moving to async without stopping to re-evaluate if it’s necessary for EF specifically.Misreading the official documentation
While Microsoft’s docs clearly state that failed saves throwDbUpdateException, not everyone digs into the details. Some might only notice the line about the method returning "the number of state entries written to the database" and assume a 0 means the save failed, rather than realizing it just means there was nothing to save in the first place.
A critical note: This check won’t catch actual save failures—those will still throw exceptions. You’ll still need to wrap SaveChangesAsync() in a try/catch block to handle errors like constraint violations, connection issues, or database-level failures. The > 0 check only tells you if rows were affected, not if the operation succeeded.
内容的提问来源于stack exchange,提问作者Renzo Rodrigues

