Pros and cons of testing for differences vs. directly updating an entity [closed]

5 days ago 2
ARTICLE AD BOX

I'm working on updating a database table from an external source, with Entity Framework Core to access the database.

The table T_CAT looks like this:

CAT_NAME varchar(20) Not Null, CAT_FUR_COLOR varchar(30) Null, CAT_FUR_PATTERN varchar(30) Null, CAT_EYE_COLOR varchar(30) Null, [...]

The corresponding entity is:

public class Cat { public string Name { get; set; } public string FurColor { get; set; } public string FurPattern { get; set; } public string EyeColor { get; set; } }

For brevity's sake, I'm leaving out the parts called by OnModelCreating() that specify, among other things, that Name is required and has a maximum length of 20.

The update method reads an external source in a loop, creating a Cat object from the data it reads. Then it updates the database according to the existing data:

Cat existingCat = CurrentContext.CatRepository.FirstOrDefault(ca => ca.CatName == catObject.CatName); if (existingCat is null) { CurrentContext.CatRepository.Add(catObject); } else { // Update database if needed }

I can see two ways to update. The obvious way feels like:

if (existingCat.CatName != catObject.CatName || existingCat.FurColor != catObject.FurColor || existingCat.FurPattern != catObject.FurPattern || existingCat.EyeColor != catObject.EyeColor /* || [...] */ ) { existingCat.CatName = catObject.CatName; existingCat.FurColor = catObject.FurColor; existingCat.FurPattern = catObject.FurPattern; existingCat.EyeColor = catObject.EyeColor; // [...] }

But the documentation indicates that

existingCat.CatName = catObject.CatName; existingCat.FurColor = catObject.FurColor; existingCat.FurPattern = catObject.FurPattern; existingCat.EyeColor = catObject.EyeColor; // [...]

would work fine, too, with CurrentContext.SaveChanges() updating the database row only if there are differences.

What are the pros and cons of either approach?

Read Entire Article