3

我的項目涉及到創建一個新的酒店房間,我的數據庫中的2個表格會更新。我的表格被稱爲RoomType和RoomFacility。如何更新相關表格?

我可以成功更新RoomType,但當我嘗試更新RoomFacility並使用RoomTypeID創建新的房間設施時,它會失敗。我總是得到1我的RoomFacilityID。

如何更新表格,roomType和RoomFacility的數據?

這是我服務的代碼來更新我的數據庫

public void UpdateFacilityInRooms(List<int> FacilityIDs, int RoomTypeID) 
    { 
     List<HotelRoomFacility> hotelRoomFacilities = 
          _HotelRoomFacilityRopository.AsQueryable() 
          .Where(f => f.RoomTypeID == RoomTypeID).ToList(); 

     foreach (int newRoomFacility in FacilityIDs) 
     { 
      if (hotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacility).Count() == 0) 
      { 
       HotelRoomFacility facility = new HotelRoomFacility 
       { 
        RoomFacilityID = newRoomFacility, 
        RoomTypeID = RoomTypeID 
       }; 
       _HotelRoomFacilityRopository.Add(facility); 
      } 
     } 
     _HotelRoomFacilityRopository.CommitChanges(); 
    } 




public RoomType NewRoom(int HotelID,int? RoomTypeID, 
         string RoomTypeName, string RoomTypeDescription) 
    { 
     RoomType room = new RoomType(); 
     room.HotelID = HotelID; 
     room.RoomTypeID = RoomTypeID ?? 0; 
     room.RoomtypeName = RoomTypeName; 
     room.RoomTypeDescripton = RoomTypeDescription; 

     _RoomTypeRepository.Add(room); 

     _RoomTypeRepository.CommitChanges(); 

     return room; 
     } 
+0

您正在使用實體框架,是嗎? –

+0

是的,我使用EF。 –

+0

然後我想這個問題會幫助你http://stackoverflow.com/q/7609721/1411687或者這個http://stackoverflow.com/q/13973836/1411687 –

回答

0
public RoomType UpdateRoom(int RoomTypeID, string RoomTypeName, string RoomTypeDescription, List<int> RoomFacilityIDs) 
     { 

      RoomType roomType = (from rt in _RoomTypeRepository.AsQueryable().Include(r => r.HotelRoomFacilities) 
           where rt.RoomTypeID == RoomTypeID 
           select rt).FirstOrDefault(); 

      if (roomType == null) 
       return null; 

      roomType.RoomTypeName = RoomTypeName; 
      roomType.RoomTypeDescripton = RoomTypeDescription; 

      //Add New Room facilities 
      List<HotelRoomFacility> hotelRoomFacilities = _HotelRoomFacilityRopository.AsQueryable().Where(f => f.RoomTypeID == RoomTypeID).ToList(); 
      foreach (int newRoomFacilityID in RoomFacilityIDs) 
      { 
       if (roomType.HotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacilityID).Count() == 0) 
       { 
        roomType.HotelRoomFacilities.Add(new HotelRoomFacility 
        { 
         RoomFacilityID = newRoomFacilityID 
        }); 
       } 
      } 


      foreach (HotelRoomFacility roomFacility in hotelRoomFacilities) 
      { 
       if (RoomFacilityIDs.Contains(roomFacility.RoomFacilityID) == false) 
        _HotelRoomFacilityRopository.Delete(roomFacility); 
      } 

      _RoomTypeRepository.Attach(roomType); 
      _RoomTypeRepository.CommitChanges(); 

      return roomType; 
     }