Entity Framework validation with partial updates

前端 未结 3 1607
长发绾君心
长发绾君心 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.

提交回复
热议问题