Entity Framework validation with partial updates

前端 未结 3 1600
长发绾君心
长发绾君心 2020-11-27 05:48

I\'m using Entity Framework 5.0 with DbContext and POCO entities. There\'s a simple entity containing 3 properties:

public class Record
{
    public int Id {         


        
相关标签:
3条回答
  • 2020-11-27 05:58

    If you use partial updates or stub entities (both approaches are pretty valid!) you cannot use global EF validation because it doesn't respect your partial changes - it always validates whole entity. With default validation logic you must turn it off by calling mentioned:

    dbContext.Configuration.ValidateOnSaveEnabled = false
    

    And validate every updated property separately. This should hopefully do the magic but I didn't try it because I don't use EF validation at all:

    foreach(var prop in propsToUpdate) {
        var errors = contextEntry.Property(prop).GetValidationErrors();
        if (erros.Count == 0) {
            contextEntry.Property(prop).IsModified = true;
        } else {
            ...
        }
    }
    

    If you want to go step further you can try overriding ValidateEntity in your context and reimplement validation in the way that it validates whole entity or only selected properties based on state of the entity and IsModified state of properties - that will allow you using EF validation with partial updates and stub entities.

    Validation in EF is IMHO wrong concept - it introduces additional logic into data access layer where the logic doesn't belong to. It is mostly based on the idea that you always work with whole entity or even with whole entity graph if you place required validation rules on navigation properties. Once you violate this approach you will always find that single fixed set of validation rules hardcoded to your entities is not sufficient.

    One of things I have in my very long backlog is to investigate how validation affects speed of SaveChanges operation - I used to have my own validation API in EF4 (prior to EF4.1) based on DataAnnotations and their Validator class and I stopped using it quite soon due to very poor performance.

    Workaround with using native SQL has same effect as using stub entities or partial updates with turned off validation = your entities are still not validated but in addition your changes are not part of same unit of work.

    0 讨论(0)
  • 2020-11-27 05:59

    In reference to Ladislav's answer, I've added this to the DbContext class, and it now removes all the properties that aren't modified.
    I know its not completely skipping the validation for those properties but rather just omitting it, but EF validates per entity not property, and rewriting the entire validation process anew was too much of hassle for me.

    protected override DbEntityValidationResult ValidateEntity(
      DbEntityEntry entityEntry,
      IDictionary<object, object> items)
    {
      var result = base.ValidateEntity(entityEntry, items);
      var falseErrors = result.ValidationErrors
        .Where(error =>
        {
          if (entityEntry.State != EntityState.Modified) return false;
          var member = entityEntry.Member(error.PropertyName);
          var property = member as DbPropertyEntry;
          if (property != null)
            return !property.IsModified;
          else
            return false;//not false err;
        });
    
      foreach (var error in falseErrors.ToArray())
        result.ValidationErrors.Remove(error);
      return result;
    }
    
    0 讨论(0)
  • 2020-11-27 06:19

    This is a remix of previous @Shimmy response and it's a version that I currently use.

    What I've added is the clause (entityEntry.State != EntityState.Modified) return false; in the Where:

    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
    {
        var result = base.ValidateEntity(entityEntry, items);
    
        var falseErrors = result
            .ValidationErrors
            .Where(error =>
            {
                if (entityEntry.State != EntityState.Modified) return false;
                var member = entityEntry.Member(error.PropertyName);
                var property = member as DbPropertyEntry;
                if (property != null) return !property.IsModified;
                return false;
            });
    
        foreach (var error in falseErrors.ToArray())
        {
            result.ValidationErrors.Remove(error);
        }
    
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题