ASPNETCore-WebAPI-Sample icon indicating copy to clipboard operation
ASPNETCore-WebAPI-Sample copied to clipboard

Entity Framework. Save question

Open XmyriyCat opened this issue 3 years ago • 1 comments

Hi, I have a little question. You have the Save method in the FoodSqlRepository class. However, this method always return positive number from 0, because the returned number is the number of state entries written to the database.
In which cases can the returned number be negative?
public class FoodSqlRepository : IFoodRepository
{
        // your code

        public bool Save()
        {
            return (_foodDbContext.SaveChanges() >= 0);
        }
}

XmyriyCat avatar Dec 17 '22 15:12 XmyriyCat

Hi,

Thank you for your question. In the context of Entity Framework (or most ORMs), the SaveChanges() method returns the number of state entries written to the database. This number will always be zero or positive, as it represents the count of affected rows.

The method signature for SaveChanges() is:

public int SaveChanges();

It returns an integer indicating how many entities were updated in the database.

  • A return value of 0 means no changes were made.
  • A positive return value means that number of changes were successfully saved.
  • It is not possible for SaveChanges() to return a negative number, as it would not make sense in the context of counting affected rows.

Regarding the Save method in the FoodSqlRepository class, it is checking whether the return value of SaveChanges() is greater than or equal to 0, which will always be true because SaveChanges() cannot return a negative number. So the method as currently implemented will always return true as long as SaveChanges() doesn't throw an exception.

Your observation is correct. If you are looking to check for a successful save operation, the method's current implementation already ensures this by verifying that the number of state entries written to the database is non-negative.

If you have further questions or need additional clarifications, feel free to ask!

iamcymentho avatar Jul 10 '24 11:07 iamcymentho