0

I'm trying to improve the performance when writing/changing data in the database using EntityFramework 6.

When fetching the entity to be updated I use the following code as I know the primary key from other entities foreign-key relation:

// create a dummy entity
var dummy = new TheEntity
{
    TheEntityId = myKey
};

// check if not already attached
var attachedEntity = dbContext.TheEntity.Exists(nrp => nrp.TheEntityId == myKey); // this checks if not already attached
if (attachedEntity == null)
{
    // attach to the context
    dbContext.TheEntity.Attach(dummy);
}

// return the dummy
return dummy;

Later I change some values of the entity (but only some) which can be different depending on the caller.

However, when SaveChanges is called I always get System.Data.Entity.Validation.DbEntityValidationExceptions for properties I did not touch.

What I want is an update-statement which only updates the values marked as IsModified == true.

I also checked the entry's properties with dbContext.Entry(dummy).Property(...).IsModified and only those I have changed are true but the other properties are false so they should not get updated, no?

What is wrong? As described here it should work as expected.

I tried the answer as well as the comment 'If you don't want to set db.Configuration.ValidateOnSaveEnabled = false...', but still the same issue. And I really do not want to disable validate.

Community
  • 1
  • 1
KingKerosin
  • 3,639
  • 4
  • 38
  • 77
  • I don't think you can do this without disabling ValidateOnSave, because validation procedure does not look if property was modified or not - just validates them all. – Evk Mar 02 '17 at 11:21
  • @Evk, thanks. I had a look at https://dennymichael.net/2016/02/03/entity-framework-validation-with-partial-updates/. Is this okay to do or are there any cases this could go completely wrong? Could not imagine such a case but may not see the whole picture here – KingKerosin Mar 02 '17 at 11:33
  • Looks fine for me. Though if you want to be on a safe side, you can disable ValidateOnSave when you perform that partial update, then manually call ctx.GetValidationErrors() and filter them out. – Evk Mar 02 '17 at 11:59
  • Hi @KingKerosin why not to read this entity from Db and update that in this way you will have all properties and validation will not fail ? – Yashveer Singh Mar 02 '17 at 12:01
  • @YashveerSingh, because for my understanding of better performance it is not necessary to fetch 20 properties/values from the db when I only want to change one or two. For this particluar problem I am not interested in the current values at all. But I know this is the way EF works... Maybe in EF7? – KingKerosin Mar 02 '17 at 12:49

0 Answers0