Getting exact error type in from DbValidationException

后端 未结 6 1058
闹比i
闹比i 2020-12-02 03:24

I have the situation where I\'m initializing my model in DatabaseInitializer() for EF 4.1 and get this annoying error \"Validation failed for one or more entities. See

6条回答
  •  悲哀的现实
    2020-12-02 03:57

    The best solution in my opinion, is to handle this kind of errors in a centralized way.

    just add this method to the main DbContext class :

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
            throw new DbEntityValidationException(errorMessages);
        }
    }
    

    This will overwrite your context's SaveChanges() method and you'll get a comma separated list containing all the entity validation errors.

    hope this is helpful.

提交回复
热议问题