How to update only one field using Entity Framework?

前端 未结 16 1830
后悔当初
后悔当初 2020-11-22 09:09

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 09:31

    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

提交回复
热议问题