使用c#检索父/子查询结果SQL Server

时间:2011-08-23 11:15:55

标签: c# sql-server linq tsql sql-server-2008

我现在在这里做的可能是满足我要求的最糟糕的方式,但我还没有找到任何其他方式。

这是我的示例数据库结构;

enter image description here

以下是我用来检索特定值的脚本;

SELECT DISTINCT h.HotelID, h.HotelName, r.RoomCode, r.RoomName, r.RoomID 
FROM RoomsInHotel rh 
INNER JOIN Hotels h ON rh.HotelID = h.HotelID 
INNER JOIN  Rooms r ON rh.RoomID = r.RoomID 
order by h.HotelName, r.RoomCode;

以上脚本给我回复的结果;

enter image description here

直到这里一切都很好。

我需要从这里转到C#代码。我想要实现的是以下结果;

enter image description here

这是我担心的地方。我使用Linq来实现这个功能,下面的代码是我用于上述控制台结果的代码。

    public class Hotel { 
      public int HotelID {get; set; }
      public string HotelName {get; set; }
      public IQueryable<Room> Rooms {get; set; }
    }

    public class HotelWithOneRoom {
        public int HotelID { get; set; }
        public string HotelName { get; set; }
        public Room Room { get; set; }
    }

    public class Room { 
      public int RoomID {get; set; }
      public string RoomCode {get; set; }
      public string RoomName { get; set; }
    }

    class Program {

        static void Main(string[] args) {

            #region _assets

            IList<HotelWithOneRoom> tempHotelWithOneRoom = new List<HotelWithOneRoom>();
            IList<Hotel> tempDistinctHotels = new List<Hotel>();
            IList<Room> tempRooms = new List<Room>();

            #endregion

            #region _connectionString

            var connectionString = "Data Source=TOSHIBA-PC\\SQLEXPRESS;Initial Catalog=tbAccomm;Integrated Security=True";

            #endregion

            using (SqlConnection conn = new SqlConnection(connectionString)) {

                using(SqlCommand cmd = conn.CreateCommand()) {

                    #region _connect to db, generate script and retrieve values

                    cmd.CommandText = "SELECT DISTINCT h.HotelID, h.HotelName, r.RoomCode, r.RoomName, r.RoomID FROM RoomsInHotel rh INNER JOIN Hotels h ON rh.HotelID = h.HotelID INNER JOIN Rooms r ON rh.RoomID = r.RoomID order by h.HotelName, r.RoomCode;";
                    cmd.CommandType = System.Data.CommandType.Text;

                    conn.Open();
                    SqlDataReader r = cmd.ExecuteReader();

                    #endregion

                    #region _assigning the values to tempHotelWithOneRoom

                    while (r.Read()) {

                        tempHotelWithOneRoom.Add(new HotelWithOneRoom {
                            HotelID = int.Parse(r["HotelID"].ToString()),
                            HotelName = r["HotelName"].ToString(),
                            Room = new Room {
                                RoomID = int.Parse(r["RoomID"].ToString()),
                                RoomCode = r["RoomCode"].ToString(),
                                RoomName = r["RoomName"].ToString()
                            }
                        });
                    }

                    #endregion

                    foreach (var item in tempHotelWithOneRoom) {

                        if (tempDistinctHotels.Where(x => x.HotelID == item.HotelID).Count() < 1) {

                            tempDistinctHotels.Add(new Hotel { 
                                HotelID = item.HotelID,
                                HotelName = item.HotelName
                            });

                            var _tempHotel = tempDistinctHotels.Single(x => x.HotelID == item.HotelID);
                            var _tempRoomList = new List<Room>();

                            if (_tempHotel.Rooms != null) { 
                                foreach (var _item in _tempHotel.Rooms) {
                                    _tempRoomList.Add(_item);
                                }
                            }

                            _tempRoomList.Add( new Room { 
                                RoomCode = item.Room.RoomCode,
                                RoomID = item.Room.RoomID,
                                RoomName = item.Room.RoomName
                            });

                            _tempHotel.Rooms = _tempRoomList.AsQueryable();

                        } else {

                            var _tempHotel = tempDistinctHotels.Single(x => x.HotelID == item.HotelID);
                            var _tempRoomList = new List<Room>();

                            if (_tempHotel.Rooms != null) { 
                                foreach (var _item in _tempHotel.Rooms) {
                                    _tempRoomList.Add(_item);
                                }
                            }

                            _tempRoomList.Add( new Room { 
                                RoomCode = item.Room.RoomCode,
                                RoomID = item.Room.RoomID,
                                RoomName = item.Room.RoomName
                            });

                            _tempHotel.Rooms = _tempRoomList.AsQueryable();
                        }
                    }

                    #region _output the result

                    foreach (var item in tempDistinctHotels) {

                        Console.WriteLine(
                            "Hotel Name : " + item.HotelName + ", " +  "Room Count : " + item.Rooms.Count()
                            );

                        foreach (var item2 in item.Rooms) {
                            Console.WriteLine("--" + item2.RoomCode + ", " + item2.RoomName);
                        }
                    }

                    #endregion

                    r.Close();
                    Console.Read();
                }

            }

        }
    }

国际海事组织,如果对最差的c#代码进行竞争,我将使用此代码赢得竞争。 (我会吗?)

那么,做我做的最优化的方式是什么?

4 个答案:

答案 0 :(得分:3)

C#不是我选择的语言,但是你去了:

Dictionary<int, Hotel> Hotels = new Dictionary<int, Hotel> ();
while (r.Read()) {
    if (!Hotels.ContainsKey(r["HotelID"])) {
        NewHotel Hotel= new Hotel();
        NewHotel.HotelID = r["HotelID"];
        Newhotel.HotelName = r["HotelName"];
        NewHotel.Rooms = new Dictionary<int, Room> ();
        Hotels.Add(NewHotel);
    }
    Room NewRoom = new Room();
    NewRoom.RoomID = r["RoomName"];
    NewRoom.RoomCode = r["RoomCode"];
    NewRoom.RoomName = r["RoomName"];
    Hotels.Items("HotelID").Rooms.Add(NewRoom);
}

就像jpmcclung指出的那样,你需要一些软件工程技能来创建成功的应用程序。您的项目越大,需要的设计和规划就越多。

答案 1 :(得分:1)

绕过编写这样的代码的最佳方法是研究测试驱动设计的实践。这段代码为此尖叫。为了看到它的实际效果,我会在TekPub(http://shop.tekpub.com/products/ft_tdd_wilson)查看Brad Wilson的新TDD Full Throttle视频,这是12块钱,但值得。否则就会有很多资源。

具体来说,为什么需要HotelWithOneRoom?只需在普通酒店的房间列表中添加一个房间。为什么不在酒店上覆盖.ToString()并使用StringBuilder为酒店创建输出线?这些只是我头脑中的一些事情,但如果您使用TDD,它将有助于组织您的设计实践并获得一些代码。

答案 2 :(得分:1)

由于您在示例中包含了IQueryable,我们是否可以假设LINQ to SQL或EF是您的解决方案的一个选项?如果是这样,请认识到他们支持直接投射到对象层次。

假设您在表之间设置了关联,可以这么简单:

var query = from hotel in context.hotels
             select new Hotel { HotelID = hotel.HotelID,
                                HotelName = hotel.HotelName,
                                Rooms = (from room in hotel.Rooms
                                        select new Room { 
                                            RoomID = room.RoomID,
                                            RoomCode = room.RoomCode, 
                                            RoomName = room.RoomName })
                                        .Distinct()
             }; 

答案 3 :(得分:0)

我认为你可以从头开始,通过重命名你的表来避免一些混乱。我认为你的桌面名称应该是Hotel,Room和RoomType(我不是多元化表名的粉丝,但这不是重点)。

以“域名”术语来思考,您有一个酒店。酒店有客房。每个房间都被定义为一种房间,双人房,单人房等......

无论如何,我把一些代码放在一起,就像你正在做的那样。我觉得它更清晰一些。 对于数据库访问,我使用了Massive https://github.com/robconery/massive因为它快速而有趣。

无论如何,这是我提出的代码。

    class Program {
        static void Main(string[] args) {
            const string sqlStmnt = @"SELECT h.HotelID, h.HotelName, r.HotelRoomID, rt.RoomTypeCode, rt.RoomTypeName FROM Hotel h INNER JOIN HotelRoom r ON r.HotelID = h.HotelID INNER JOIN  RoomType rt ON r.RoomTypeID = rt.RoomTypeID order by h.HotelName, rt.RoomTypeCode";
            var context = new HotelContext();
            var hotelData =  context.Query(sqlStmnt);
            var hotelList = new List<Hotel>();

            //Load our objects
            foreach (dynamic data in hotelData) {
                int hotelID = data.HotelID;
                var hotel = hotelList.Where(h => h.HotelID == hotelID).FirstOrDefault()
                                      ?? new Hotel() {HotelName = data.HotelName};
                hotel.AddRoom(new HotelRoom { HotelRoomID = data.HotelRoomID, RoomType = new RoomType{ TypeCode = data.RoomTypeCode, TypeDescription = data.RoomTypeName}});

                if (hotel.HotelID != 0) {continue;}
                hotel.HotelID = hotelID;
                hotelList.Add(hotel);
            }

            //Display our output
            foreach (var hotel in hotelList) {
                Console.WriteLine("Hotel Name : " + hotel.HotelName + ", Room Count : " + hotel.HotelRooms.Count());
                foreach (var room in hotel.HotelRooms) {
                    Console.WriteLine("--" + room.RoomType.TypeCode + ", " + room.RoomType.TypeDescription);
                }
            }

            Console.ReadLine();
         }
    }

这是我的数据库内容。

    public class HotelContext : DynamicModel {
        public HotelContext():base("test") {
        PrimaryKeyField = "HotelID";
        TableName = "Hotel";
        }
    }

以下是我使用的课程。无法弄清楚你的HotelWithOneRoom是什么意思。

    public class Hotel{
        private readonly List<HotelRoom> _rooms = new List<HotelRoom>();
        public int HotelID { get; set; }
        public string HotelName { get; set; }
        public void AddRoom(HotelRoom room) {_rooms.Add(room);}
        public IQueryable<HotelRoom> HotelRooms {get {return _rooms.AsQueryable();}}
    }
    public class HotelRoom {
        public int HotelRoomID { get; set; }
        public RoomType RoomType { get; set; }
    }

    public class RoomType {
        public string TypeCode { get; set; }
        public string TypeDescription { get; set; }
    }