Search code examples
c#asp.netentity-frameworkcode-first

Update and fetch a record from Entity Framework in a single query


I am working on a hotel management system and I am trying to make a query which will check the booking timing, and if the timing is over, it will close the booking and return a room type.

Close the booking means it will turn it's status to false and it will return a room type now the problem is that this query:

var Records = db.BookingInformation
                .Where(t => t.EndDate <= serverDate)
                .Where(t => t.Booking == true)
                .Select(t => t.RoomType).ToList();

This is returning a room type, but it's not turning booking to false. Any help?

I know that I haven't tried to update booking but I don't know how to do it.


Solution

  • Try this out, should do what you are asking for:

    var records = db.BookingInformation
        .Where(t => t.EndDate <= serverDate)
        .Where(t => t.Booking == true).ToList()
          .Select(t => {t.Booking = false; return t.RoomType;});
    

    Call SaveChanges after executing this, otherwise the changes will not be persisted to the DB.