Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update list from another list - entity framework

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

like image 445
Gopi Avatar asked Sep 21 '26 06:09

Gopi


2 Answers

For another awswer

    foreach (var room in updateRooms)
    {
        dbContext.Entry(room).State = EntityState.Modified;
    }
    dbContext.SaveChanges();

You also use this.

like image 174
Aixasz Avatar answered Sep 22 '26 19:09

Aixasz


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();
like image 23
Mahendra Avatar answered Sep 22 '26 20:09

Mahendra