Home >Database >Mysql Tutorial >How to Update a Single Field in Entity Framework?

How to Update a Single Field in Entity Framework?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-19 07:14:12560browse

How to Update a Single Field in Entity Framework?

Entity Framework single field update method

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 UserIdPassword field for a specific user, you can use the and methods of AttachDbContextProperty.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn