views:

82

answers:

2

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.

+1  A: 

Where are you creating the instance variable DB?

model.DB = DB

Where is the right DB getting initialized?

Dismissile
Good question. The first post is updated.
Alex
+2  A: 

You may want to rename IValidated to ValidationBase or something - the I prefix denotes an interface rather than a base class.

Is DB being set up in your controller's constructor? I'm guessing it's not, which leads to the Register method assigning a null reference to model.DB which leads to your NullReferenceException.

Also, MVC2 will read properties during databinding to try to validate them. That's probably what's biting you. If you change IsValid from a property to a method, the problem will go away.

48klocs
You are right, the DB object is null even when I create it right in the Register method. According to the debugger, the error takes place before Register method is run, so IsValid method is run before the ActionResult is loaded! That's why DB is null and I have no clue how to fix this.
Alex
Thanks for addition! I turned IsValid into a method, and it's working fine. Now I understand why it happened.Thanks again.
Alex