Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Entity Framework. Save question #16

Open
XmyriyCat opened this issue Dec 17, 2022 · 1 comment
Open

Entity Framework. Save question #16

XmyriyCat opened this issue Dec 17, 2022 · 1 comment

Comments

@XmyriyCat
Copy link

XmyriyCat commented Dec 17, 2022

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);
        }
}
@iamcymentho
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants