The question is easier to understand, if you immediately look at the code

static int Reset() { using (ApplicationContext db = new ApplicationContext()) { return db.Database.ExecuteSqlCommand("UPDATE Employees SET StatusCode=0 WHERE StatusCode>0"); } } 

Is it possible to create an update request using EF tools (one request, and not first read into memory, change and call db.SaveChanges() - I think this is extremely inefficient), or use ExecuteSqlCommand() in such cases - the only solution?

    3 answers 3

    Look at the EntityFramework.Extended package - it seems that it does exactly what you need.

    But it should be noted that "batch" operations are not friendly with the context cache - that is, there may be a conflict when saving if you first update the record with a batch operation and then try to save it in the usual way. Use batch operations if you know what you are doing.

      No, just as you already wrote, through a normal SQL query. Entity Framework is an Entity that works with entities. Without getting the entity, nothing happens. But do not forget to update your data in the program later. Then you also get 2 requests.

      • But do not forget to update your data in the program later. Then you will also get 2 requests - can you elaborate on the second request? didn't quite get it - Qutrix
      • @Qutrix You have updated the objects in the database. If you want to continue using them in the program, you will have to request them. And so they would have already been updated in the program. Of course, if you do not use them anymore, the SQL query is preferable. - RusArt
      • If the request is not very complex and there is not much data - I think it’s faster to change the data in the program itself - Qutrix

      I also found a way for cases when you know the id of the object to be deleted.

       var toDelete = new Destination { DestinationId = 2 }; context.Destinations.Attach(toDelete); context.Destinations.Remove(toDelete); context.SaveChanges();