I have a problem in my UserRepository in which I want to update a user. I dont want certain fields updated, such as password, unless specified. For example, When I pass the User from the view, to the service to the repository, it sends up the user with a null or empty password string. This null gets written to the database (which I dont want).
How do I handle a situation like this?
Domain
public class User
{
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Repository
public User Save(User user)
{
if (user.UserId > 0)
{
User dbUser = context.Users.FirstOrDefault(u => u.UserId == user.UserId);
//What do I do here?
}
context.Users.AddObject(user);
context.SaveChanges();
return user;
}
Lets say in this case, my view allows me to change only Email, so the only thing that gets sent back to the Save() method are: user.UserId and user.Email while user.Password is null. In my case, the database throws error because Password should be nullable.
Detached POCO scenario (you will not load user from DB before update):
You can selectively say which properties must be updated:
You can also create two overloads of you
Savemethod. First will update whole object, second will update only explicitly selected properties:You will call the second overload this way:
Attached scenario (you will load user from DB before update):
You can modify your Save method to accept delegate so that you can control how update will be performed:
You will call the method this way:
Anyway, despite of my examples you should definitely think about Darin’s post and special ModelViews for updating.