2

Working with ASP .NET MVC I have a model called Entity1 and I need to do a custom validation inside of it.

I searched for a while and found out that implementing IValidatableObject I could implement the Validate method to do what I want. Now the question I have in this process is that I need to validate a property of Entity1 with another property of related Entity2 (by related I mean Data base relationship).

What I have is this:

public partial class Entity1: IValidatableObject
{
    private EntitiesContext db = new EntitiesContext ();

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!Validation1())
        {
            yield return new ValidationResult(@"Error message.", new[] { "Property1" });
        }
    }

    private bool Validation1()
    {
        if (this.Property1 != db.Entity2.First().Property2)
        {
            return false;
        }

        return true;
    }
}

This is a simplified example of what I'm trying to do, but what I'm trying to figure out is if the use of "db" object to make the validation is well done right there. Obviously I can polish it later with some Dependency Injection, but I want to be sure if this is the right way to make that kind of validation or if another way exists to achieve exactly that.

PS: I tried to access the relationship like this too, but the relationship is always null:

this.Property1 != this.Entity2.Property2

In the later, this.Entity2 is always null.

Thanks in advance! :)

Felipe Correa
  • 654
  • 9
  • 23
  • 2
    Briefly discussed this [here](http://stackoverflow.com/a/31527559/861716). – Gert Arnold Aug 18 '15 at 21:40
  • @GertArnold don't know what's wrong on my side but `validationContext.Items.Count` is zero when it reaches the `Validate` method. – Felipe Correa Aug 18 '15 at 21:54
  • Forgot an essential part, see the edited answer over there. – Gert Arnold Aug 18 '15 at 22:18
  • @GertArnold Ok so I overwrote that method in my DbContext, still doesn't work. I set a breakpoint inside of it and it never gets hit so so the `Items` property of `validationContext` is still zero. Reviewed everything and didn't get to what's wrong... any ideas? – Felipe Correa Aug 19 '15 at 00:48

0 Answers0