How to set custom validation just where Entry.state == EntityState.Added

前端 未结 3 2140
花落未央
花落未央 2020-12-12 03:42

How to set custom validation that when Entry.state == EntityState.Added is true the below code would work! Custom Validation Code:

         


        
3条回答
  •  渐次进展
    2020-12-12 04:03

    @Gert Arnold post is a way,and if you want use attribute,you can find the object from ValidationContext by ObjectInstance property

    var user = validationContext.ObjectInstance as User;
    if(user==null) return new ValidationResult("...");
    using(var db=new SomeDbContext()){
        var has=db.User.Any(x=>x.Id!=user.Id && x.email==value);
        if (has) return new ValidationResult("...");
        else return ValidationResult.Success;
    }
    

    when add,the id is 0,so in db,there is not a id 0 record,so if there is 1 record has same email,the any() return true.
    when update,you have a id,so x.id!=user.id can except this record self.

提交回复
热议问题