Entity Framework Validation

前端 未结 6 1540
情话喂你
情话喂你 2020-12-14 09:58

I\'m getting ready to start a new project and I\'ve been researching the entity framework. My question is what is the best strategy for validating the entities? Other projec

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 10:21

    We have overrident the object context and intercept the SaveChanges() method

    public abstract class ValidationObjectContext : ObjectContext{
        ...
    
        public override int SaveChanges(SaveOptions options){
            ValidateEntities();
            return base.SaveChanges(options);
        }
    
    }
    

    That way the validation is left until the last minute before the connections are made but after you are (expecting) to be happy with the graph and ready to commit, (as opposed to other options to validation on any change, since some complex rules like those we have are only valid after several properties are set.). We have two levels of validation, Basic Property validation, things like string length, nullability etc. And Business Logic validation, which might require checking rules across multiple objects, possibly hitting the database to confirm.

提交回复
热议问题