3

I am trying to use a DBContext to automatically validate my entities and display a message on screen. The get validation errors successfully detects all non-nullable properties of type string as they still have a value of null. My problem arises when I try to validate a property of type int. The value is already set to 0 by default and as it is a foreign key id I need this value to not be 0,but it does not get detected.

        //Create a database context over current ObjectContext          
        var databaseContext = new DbContext(this, true);

        //Get Validation Errors
        var errors = databaseContext.GetValidationErrors();

        //Display errors on screen
        if (errors.Any())
        {
            var errorList = new StringBuilder();

            foreach (var error in errors)
            {
                foreach (var validationError in error.ValidationErrors)
                {
                    errorList.AppendLine(validationError.ErrorMessage);
                }
            }

            var vm = IoC.Get<ModalConfirmationViewModel>();
            vm.Message = errorList.ToString();

            var wm = IoC.Get<WindowManager>();
            wm.ShowDialog(vm);

            return false;
        }

Thoughts?

Thanks Ben

2 Answers 2

9

You can use Range to validate if a property is within a specific range:

 [Range(1, int.MaxValue, ErrorMessageResourceName = "BarIdMustBeGreaterThanZero",
        ErrorMessageResourceType = typeof (Resources))]
 int BarId{ get; set; }
Sign up to request clarification or add additional context in comments.

Comments

2

Try making it a nullable int.

public class Foo
{
    [Key]
    public int Id { get; set; }

    [Required]
    public int? BarId { get; set; }

    public virtual Bar Bar { get; set; }
}

1 Comment

The properties are automatically set on the entities everytime the edmx is generated. As far as I am aware I can't manually set them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.