public List<Room> GetAllRoom()
{
List<Room> rooms = new List<Room>();
DBHelper.con.Open();
string sql = string.Format("select RoomId,BedNum,Typename,description,roomstatename,guestnum from Room,RoomState,RoomType where Room.RoomStateID=RoomState.RoomStateID and Room.RoomTypeID=RoomType.TypeID");
SqlCommand com = new SqlCommand(sql, DBHelper.con);
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
Room room = new Room();
room.RoomId = Convert.ToInt32(read[0]);
room.BedNum = Convert.ToInt32(read[1]);
room.Description =read[3].ToString();
room.GuestNum = Convert.ToInt32(read[5]);
room.RoomTypeId = GetRoomTypeIdByName(read[2].ToString()); //查出来的是typename 所以要写方法得到typeid
//room.RoomStateId = GetRoomStateIdByName(read[4].ToString()); //同上
rooms.Add(room);
}DBHelper.con.Close();
read.Close();
return rooms;
}
private int GetRoomTypeIdByName(string typename) //通过房间类型名称或者房间类型ID
{
int typeid = 0;
try
{
DBHelper.con.Open();
string sql = string.Format("select Typeid from RoomType where TypeName='{0}'", typename);
SqlCommand com = new SqlCommand(sql, DBHelper.con);
typeid = Convert.ToInt32(com.ExecuteScalar().ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
DBHelper.con.Close();
}
return typeid;
}
还有个DHHelper类中我放了一个连接字符串。。 但是走到这个位置的时候,就会报错room.RoomTypeId = GetRoomTypeIdByName(read[2].ToString());
说是阅读器关闭时 MetaData 的尝试无效 我查了一些资料,应该就是datareader的关闭的问题,就是想不出来怎么去修改,有清楚的可以麻烦告诉我一下被
------解决方案--------------------------------------------------------
你的GetRoomTypeIdByName方法里边,不是把外边的DBHelper.con的状态给破坏了嘛。再说的更实际一点,你可能从来没有用两个用户,或者同一个用户两个页面,并发测试过(任何)程序。
你去设计这类“静态、共享、多用户下自己冲突”的DBHelper.con,一看就是“那种”思路。