James I
James I

Reputation: 9

ASP.NET MVC: Updating model from within model?

In a controller, I do the following:

DBContext DB = new DBContext();
var u = DB.Users.Find(1);
u.firstname = "blah";
UpdateModel(u);
DB.SaveChanges();

I want to do the same from within a model...

namespace Project.Models
{
  public class User
  {
    public void resetPassword()
    {
      // Generate new password, etc.
      this.password = "blah";
    }
  }
}

Any idea how I go about doing this? It seems UpdateModel() is only available from within controllers.

I'm using EntityFramework Code-First CTP5.

Upvotes: 0

Views: 360

Answers (2)

Andy Gaskell
Andy Gaskell

Reputation: 31761

I think UpTheCreek is correct but it probably needs some explanation so I'll try to expand on his/her answer. The first step would be to use the repository pattern. You can find many examples of this pattern in MVC with a google search - this is a particularly gentle introduction (about 3/4's down the page).

The walkthrough goes on to mention dependency injection, and that's something that's also worth looking in to. I tend to favor Ninject myself, however there are other dependency injection containers available.

Upvotes: 1

UpTheCreek
UpTheCreek

Reputation: 32391

Putting data access concerns in your model is not a good idea.

Update: Yes, you'd usually have a data access layer for this. As Andy says, the currently fashionable way to do this is using a repository. As a rule, you don't want anything in your model that is not core business logic.

Upvotes: 0

Related Questions