views:

58

answers:

2

Here's the table

Users

UserId
UserName
Password
EmailAddress

and the code..

public void ChangePassword(int userId, string password){
//code to update the password..
}
+2  A: 

You have basically two options:

  • go the EF way all the way, in that case, you would
    • load the object based on the userId provided - the entire object gets loaded
    • update the password field
    • save the object back using the context's .SaveChanges() method

In this case, it's up to EF how to handle this in detail. I just tested this, and in the case I only change a single field of an object, what EF creates is pretty much what you'd create manually, too - something like:

`UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId`

So EF is smart enough to figure out what columns have indeed changed, and it will create a T-SQL statement to handle just those updates that are in fact necessary.

  • you define a stored procedure that does exactly what you need, in T-SQL code (just update the Password column for the given UserId and nothing else - basically executes UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId) and you create a function import for that stored procedure in your EF model and you call this function instead of doing the steps outlined above
marc_s
A: 

You can say EF which properties have to be updated by this way:

public void ChangePassowrd(int userId, string password)
{
  var user = new User() { Id = userId, Password = password };
  using (var context = new ObjectContext(ConnectionString))
  {
    var users = context.CreateObjectSet<User>();
    users.Attach(user);
    context.ObjectStateManager.GetObjectStateEntry(user).SetModifiedProperty("Password");
    context.SaveChanges();
  }
}
Ladislav Mrnka