0

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.

1
  • What are you achieving using UpdateModel() here that would be related to the DB? Commented Feb 28, 2011 at 8:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is a better answer than mine :)
0

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.

1 Comment

How about from a non-controller class, where I get the same issue? It's obviously wrong to call a function in one controller from another controller, so logically I'd encapsulate this into a library class..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.