I've been struggling for this for an hour and I don't understand why there's a problem.
I have an abstract class
public abstract class IValidated
{
public bool IsValid { get { return (GetRuleViolation() == null); } }
public abstract RuleViolation GetRuleViolation();
}
And a validation class
public class RegisterModel : IValidated
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public MyDataContext DB { get; set; }
// ....
}
When I use the validation, I get an error
public ActionResult Register(RegisterModel model)
{
model.DB = DB;
if (model.IsValid) // an exception here
}
DB is null! I need to pass the datacontext object to the validation to check if the e-mail is unique and stuff like that.
Here's how the DB is initialized:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
DB = new MyDataContext();
}
The DB property is set in the Register method, I debugged that. But in the IsValid method of the class it's null...
UPDATE
Looks like the MVC framework for some reason runs the IsValid method before the Register ActionResult (and before the DB object is initialized). I think it's because it's doing all "magic" stuff with passing the RegisterModel parameters to the view. So I just put
if (DB != null)
and it helped.
Apparently, the IsValid method is run again when I call it, and the DB object is not null by then.
UPDATE 2
Since IsValid was a property, ASP.NET MVC was binding it, after turning it into a method, the problem disappeared.