更新时间:2022-11-05 08:12:49
这是一种方式,我希望它可以帮助你
var room =(from g in m3d.rooms
其中g.RoomNo == RoomNo
select g).FirstOrDefault(); //取一个objecto空间修改
room.FK_Stations = StationID;
foreach(BedsDataGridView.Rows中的DataGridViewRow行)
{
int Bedno = row.Cells [0] .Value.ToString();
var bedsChanged =(from g in m3d.beds
其中g.bedno == Bedno
选择g).FirstOrDefault();
bedsChanged.FullRoomNo = row.Cells [1] .Value.ToString();
bedsChanged.RoomStatus =Available;
}
m3d.SaveChanges();
My project is Windows Application c#, I am using Entity Framework 5 and .net 4.5.
I have Rooms and Beds module which you can add, edit and delete Room(s) and/or bed(s)
on my Form I have a field for RoomNo and Station, also Add and Delete button to add/delete bed(s) to datagridview, then Save button to save the Room and list of beds to DB
DB Structure
Rooms (table)
PK_Rooms
FK_Station
RoomNo
Beds (table)
PK_Beds
FK_Rooms
BedNo
FullRoomNo (concat only of Roomno and Bedno)
RoomStatus
I already implemented the "AddRoom" method which will create new Room and list of beds.
my question is how can i implement "EditRoom" method which will detect changes on the beds (added a new bed, AND/OR edited a bed number, AND/OR deleted a bed) and save it to DB?
To have a better understanding to my concern please see previous thread, which also has the AddRoom Method > Entity Framework only saving last row (master details)
Edit: here is my code to EditRoom method
M3dEntities m3d = new M3dEntities();
rooms rooms = new rooms();
beds beds = new beds();
string RoomNo = RoomNoTxt.Text;
int StationID = Int32.Parse(StationCmb.SelectedValue.ToString());
int _SelectedPKRoom = Int32.Parse(SelectedPKRoom);
rooms = m3d.rooms.First(x => x.PK_Rooms == _SelectedPKRoom);
{
rooms.RoomNo = RoomNo;
rooms.FK_Stations = StationID;
}
foreach (DataGridViewRow row in BedsDataGridView.Rows)
{
beds = new beds();
beds.Bedno = row.Cells[0].Value.ToString();
beds.FullRoomNo = row.Cells[1].Value.ToString();
beds.RoomStatus = "Available";
m3d.beds.AddObject(beds);
m3d.beds.DeleteObject(beds);
}
m3d.SaveChanges();
the problem with this code is only room are being updated :(
This is one Way, I hope it helps you
var room= (from g in m3d.rooms
where g.RoomNo == RoomNo
select g).FirstOrDefault(); //Take an objecto room to modify
room.FK_Stations = StationID;
foreach (DataGridViewRow row in BedsDataGridView.Rows)
{
int Bedno = row.Cells[0].Value.ToString();
var bedsChanged= (from g in m3d.beds
where g.bedno== Bedno
select g).FirstOrDefault();
bedsChanged.FullRoomNo = row.Cells[1].Value.ToString();
bedsChanged.RoomStatus = "Available";
}
m3d.SaveChanges();