D
D
DailyDDose2018-03-03 13:52:36
ASP.NET
DailyDDose, 2018-03-03 13:52:36

EntityFramework - Partial update of a row in a table?

Good day.
There is a simple table in the database

CREATE TABLE [dbo].[Users]
(
    [Id] INT NOT NULL PRIMARY KEY, 
    [FirstName] VARCHAR(50) NOT NULL, 
    [LastName] VARCHAR(50) NOT NULL, 
    [Age] INT NOT NULL
)

What is the correct way to write a controller method to update one (or more columns) ?
[HttpPatch]
        public ActionResult Patch([FromBody]User userData)
        {
            var user = Db.Users.FirstOrDefault(entity => entity.Id== userData.Id);
            if (userTokenData == null)
            {
                return null;
            }
 
            user.FirstName = userData.FirstName; // ??
            Db.SaveChanges();
            return Json(user);
        }

To be able to send queries like: Only the Age column should be updated. FirstName and LastName columns should be updated.
{ Id: 1, Age: 42 }
{ Id: 1, FirstName: "Alex", LastName: "Ander" }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-03-03
@DailyDDose

_context.Entry(userData).State = EntityState.Modified;
 try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
    if (!Db.Users.Any( a => a.Id==userData.Id))
    {
        return NotFound();
    }
    else
    {
        throw;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question