我正在使用 Visual Studio Community 2013 并为我的类(class)开发一个项目,我正在制作一个非常非常简单的酒店预订系统,供员工创建新客户并将他们预订到房间。
当用户尝试两次预订同一个房间或它重叠时,我需要系统不允许它并且我正在尝试处理服务中的问题。 (见下文)
public override void Add(Booking booking)
{
// Don't allow a new booking if the room is already out.
var currentBooking = _ctx.Bookings
.Where(b => b.RoomId == booking.RoomId)
.Select(b => (b.CheckOut < booking.CheckIn
&& b.CheckIn < booking.CheckIn)
|| (b.CheckIn > booking.CheckOut
&& b.CheckOut > booking.CheckOut ))
.FirstOrDefault();
if (currentBooking != null)
{
throw new BookingException("The Room is already out on that date.");
}
booking.CheckIn = DateTime.Now.Date;
_ctx.Set<Booking>().Add(booking);
_ctx.SaveChanges();
}
我遇到的问题是,无论我在创建新预订时输入什么日期,系统都会抛出 BookingException“房间已出”,即使我的 DBseed 中只有两个日期。 (见下文)
context.Bookings.AddOrUpdate(
b => b.CheckIn,
new Booking()
{
CheckIn = new DateTime(2015, 09, 12),
CheckOut = new DateTime(2015, 09, 21),
RoomId = 1,
CustomerId = 1,
},
new Booking()
{
CheckIn = new DateTime(2015, 06, 01),
CheckOut = new DateTime(2015, 06,08),
RoomId = 2,
CustomerId = 2
});
我认为我的问题出在服务上,但我无法弄清楚具体问题是什么。
最佳答案
这个 currentBooking 是 bool 因此它总是抛出异常,即它永远不会为 null。
将 if 语句切换为检查 true 似乎突出了 Linq 中的过滤问题。我不得不说我只是重写了这个选择,我只运行了几个测试,但这似乎有效:
currentBooking = _ctx.Booking
.Where(b => b.RoomId == booking.RoomId)
.Select(b => (booking.CheckIn < b.CheckOut && booking.CheckIn > b.CheckIn))
.FirstOrDefault();
if (currentBooking)
{
throw new Exception("The Room is already out on that date.");
}
关于c# - 两个日期之间的房间可用性(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547592/