我的项目是c#Windows应用程序,我使用的是Entity Framework 5和.net 4.5。
我有房间和床模块,您可以添加,编辑和删除房间和/或床
在我的表格上我有一个RoomNo和Station的字段,还有添加和删除按钮来添加/删除床到datagridview
DB Structure
Rooms (table)
PK_Rooms
FK_Station
RoomNo
Beds (table)
PK_Beds
FK_Rooms
BedNo
FullRoomNo (concat only of Roomno and Bedno)
RoomStatus
下面是我添加房间和床位的添加方法
M3dEntities m3d = new M3dEntities();
rooms rooms = new rooms();
beds beds = new beds();
string RoomNo = RoomNoTxt.Text;
int StationID = Int32.Parse(StationCmb.SelectedValue.ToString());
var roomnoexist = from g in m3d.rooms
where g.RoomNo == RoomNo
select g;
if (roomnoexist.Any())
{
MessageBox.Show("Room No. Already Exist!");
}
else
{
rooms.RoomNo = RoomNo;
rooms.FK_Stations = StationID;
m3d.rooms.AddObject(rooms);
}
foreach (DataGridViewRow row in BedsDataGridView.Rows)
{
beds.Bedno = row.Cells[0].Value.ToString();
beds.FullRoomNo = row.Cells[1].Value.ToString();
beds.RoomStatus = "Available";
m3d.beds.AddObject(beds);
}
m3d.SaveChanges();
(例如:添加房间1201有4张床) 只有最后一排床被保存到DB。
我的问题:
答案 0 :(得分:0)
您应该在beds beds = new beds();
语句中移动foreach
指令,如下所示:
foreach (DataGridViewRow row in BedsDataGridView.Rows)
{
beds beds = new beds(); // Here is its place.
beds.Bedno = row.Cells[0].Value.ToString();
beds.FullRoomNo = row.Cells[1].Value.ToString();
beds.RoomStatus = "Available";
m3d.beds.AddObject(beds);
}
如果您总是在beds
的最后一个实例,它最终包含您的最后一行并仅保存该行。
附注:如果要像这样插入多个对象,可以使用AddRange
:
var bedsCollection = new List<beds>();
foreach (DataGridViewRow row in BedsDataGridView.Rows)
{
beds beds = new beds(); // Here is its place.
beds.Bedno = row.Cells[0].Value.ToString();
beds.FullRoomNo = row.Cells[1].Value.ToString();
beds.RoomStatus = "Available";
bedsCollection.Add(beds); // update the collection not the DbSet
}
m3d.beds.AddRange(bedsCollection);
m3d.SaveChanges();