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
Release: 2025-01-19 07:14:12
Original
561 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template