Mauricio Camacho
Mauricio Camacho

Reputation: 35

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?

Upvotes: 1

Views: 5869

Answers (2)

Hooman Bahreini
Hooman Bahreini

Reputation: 15579

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();
}

Upvotes: 2

Barr J
Barr J

Reputation: 10927

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.

Upvotes: 0

Related Questions