1

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?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
  • 3
    have a look on this link: https://stackoverflow.com/questions/21592596/update-multiple-rows-in-entity-framework-from-a-list-of-ids – Hasan Gholamali Jul 15 '18 at 05:36

2 Answers2

1

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 res = dbContext.Recibo.Where(r => r.IdApartado == 7).ToList();

    // update
    foreach (r in res)
    {
        r.Estado = 3;
    }

    // save
    dbContext.SaveChanges();
}
Hooman Bahreini
  • 12,572
  • 10
  • 52
  • 106
0

Two ways to do in clause in EF:

first is Contains:

return dbContext.Query<R>.Where(r => subset.Contains(r.Id)).ToList();

second is foreach with contains:

 return dbContext.Query<R>.Where(r => subset.Contains(r.Id)).ToList().ForEach(a => a.id = "7");

this is because the best equivalent for sql in in EF is Contains.

Barr J
  • 10,104
  • 1
  • 27
  • 44