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! :)