Room Model
public class Room
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Id is the primary key here
As in entity framework, all the room details are in the dbcontext
dbContext.Rooms
And there is a IList<Room> updateRoomswith list of updated name and address for few rooms.
How do I update dbContext.Rooms for the matching items in updateRooms using the primary key Id and save to DB using entity framework.
Note: I do understand that I can update each Room in dbContext.Rooms and save as below
foreach (var room in updateRooms)
{
dbContext.Rooms.Attach(room);
dbContext.Entry(room).State = EntityState.Modified;
dbContext.SaveChanges();
}
but is there a way attach all rooms and save at once
For another awswer
foreach (var room in updateRooms)
{
dbContext.Entry(room).State = EntityState.Modified;
}
dbContext.SaveChanges();
You also use this.
First You need to find all the entries with Id (Primary Key) and update the values. Then call SaveChanges() method.
foreach (var room in updateRooms)
{
var roomToUpdate = dbContext.Rooms.Find(room.Id);
roomToUpdate.Name = room.Name;
roomToUpdate.Address = room.Address;
}
dbContext.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With