Based on my last question, I have tried to separate the business logic from my controller completely.
This however has left a problem which I understand why, but not how to fix…. And, I do not understand why it is doing what is doing.
In my controller, I had the following:
public User GetCurrentUser()
{
User user = db.Users.SingleOrDefault(x => x.UserName == User.Identity.Name);
return user;
}
I now know about [NonAction] which fixes the security concern – however, I know this doesn’t follow best practices of not having any non controller stuff in a controller. For this reason, I moved to a new class and modified it to the following:
public User GetCurrentUser(string name)
{
User user = db.Users.SingleOrDefault(x => x.UserName == name);
return user;
}
I have an edit method which before simply set various fields in the user object, then called db.SaveChanges(). This however is now causing issues – I believe it is due to calling the command on a db object that doesn’t actually have the object loaded.
But, the part that I really do not understand is when I am redirected back to the home page and perform GetCurrentUser() again, I am presented with the edited details I changed… These are not stored in the database and it is only when I restart the application it goes back to the database results.
I am finding this very confusing! What is happening here and where are the object being stored?
And, how do I fix it? I have tried making the new Class’s db function public and calling it’s SaveChanges() method, but, this is resulting in the same problem – data that is not being saved to the database.
Anyway, quite frankly, I really liked calling it via just GetCurrentUser(), I wanted this due to the fact I wanted to change the way the user was loaded in the future – but, now that I have to call it via GetCurrentUser(User.Identity.Name), and make other modifications, I think it wouldn’t be that much harder to just skip on the method and call the Lambda query directly instead… It just seems it will save a lot of trouble.
Based on the detail in your question, you need to make sure you attaching your Entity object e.g
db.Users.Attach(updatedUser)And then change its state
e.g
db.ObjectStateManager.ChangeObjectState(updatedUser, EntityState.Modified)Before you call
db.SaveChanges()