Home >Database >Mysql Tutorial >How to Update a Single Field in Entity Framework?
Question:
Suppose you have a database table with multiple columns and you want to update the value of a specific column in the record.
Table:
Users
列名 |
---|
UserId |
UserName |
Password |
EmailAddress |
Code:
<code class="language-csharp">public void ChangePassword(int userId, string password) { // 更新密码的代码... }</code>
Answer:
To update only the UserId
Password field for a specific user, you can use the and methods of Attach
DbContextProperty
.
For versions prior to EF Core 7.0:
<code class="language-csharp">public void ChangePassword(int userId, string password) { var user = new User() { Id = userId, Password = password }; using (var db = new MyEfContextName()) { db.Users.Attach(user); db.Entry(user).Property(x => x.Password).IsModified = true; db.SaveChanges(); } }</code>
For EF Core 7.0 and above:
<code class="language-csharp">public void ChangePassword(int userId, string password) { var user = new User() { Id = userId, Password = password }; using (var db = new MyEfContextName()) { db.Users.SetAttached(user); db.Entry(user).Property(x => x.Password).IsModified = true; db.SaveChanges(); } }</code>
Note: In EF Core 7.0 and later, the Attach
method has been renamed to SetAttached
. The above code shows two versions of implementation methods. Please choose the appropriate code according to your EF Core version.
The above is the detailed content of How to Update a Single Field in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!