Search code examples
c#sqlasp.net-mvcentity-framework-6

Update Multiple Rows in Entity Framework from one id


I am trying to create a query for Entity Framework that will allow me to take one id and update a field associated with it.

Example in SQL:

UPDATE Recibo
SET Estado = 3
WHERE IdApartado IN (7)

How do I convert the above to Entity Framework?


Solution

  • There are multiple ways of doing it, perhaps, the easiest way would be to read the records, edit them and save them, as explained here:

    using (var dbContext = new DbContext())
    {
        // read 
        var records = dbContext.Recibo.Where(r => r.IdApartado == 7).ToList();
    
        // update
        foreach (r in records)
        {
            r.Estado = 3;
        }
    
        // save
        dbContext.SaveChanges();
    }