【问题标题】:Room availability between two dates (beginner)两个日期之间的空房情况(初学者)
【发布时间】:2015-05-30 14:55:32
【问题描述】:

我正在使用 Visual Studio Community 2013 并正在为我的班级开展一个项目,在该项目中我正在制作一个非常简单的酒店预订系统,供员工用来创建新客户并将他们预订到房间。

当用户尝试两次预订同一个房间或重叠时,我需要系统不允许它,我正在尝试处理服务中的问题。 (见下文)

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
            });

我认为我的问题出在服务中,但我无法弄清楚具体问题是什么。

【问题讨论】:

  • Booking booking 在您的 Add() 方法中使用了哪些特定值?

标签: c# sql service


【解决方案1】:

这个 currentBooking 是 bool 因此它总是抛出异常,即它永远不会为空。

切换 if 语句以检查是否为真似乎突出了 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.");
        }

【讨论】:

  • 现在就像一个魅力!谢谢一百万:)
猜你喜欢
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多