2

How can I convert this code to Entity Framework?

update cachieroperation set last_used = getdate()+'0:8:0' where id = 14
TylerH
  • 20,799
  • 66
  • 75
  • 101
adilet.571
  • 61
  • 2
  • 7

2 Answers2

9

Should be something like(I don't know what your classes are called):

using(var context = new SomeEntities())
{
     CarrierOperation carrierOperation = context.CarrierOperations.SingleOrDefault(co=> co.id == 14);
     if(carrierOperation != null)
     {
         carrierOperation.last_used = DateTime.Now.AddMinutes(8);
         context.SaveChanges();
     }
}
Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28
  • This answer execute a SELECT, loads all data of record (transfer from DB to application) then executes the update. I have suggested a duplicate on the question to use object model but only execute the UPDATE – Petter Friberg Jan 12 '21 at 16:19
1

You can use ExecuteQuery for executing queries directly against the database:

string query = "update cachieroperation set last_used = getdate()+'0:8:0' where id = 14";
context.ExecuteQuery<cachieroperation>(query );  

For more info, see Microsoft Docs on ExecuteQuery

TylerH
  • 20,799
  • 66
  • 75
  • 101
Amit Bisht
  • 4,870
  • 14
  • 54
  • 83