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
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 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

2

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();
}
Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
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,636
  • 1
  • 28
  • 46