c# - 两个日期之间的房间可用性(初学者)

标签 c# sql service

我正在使用 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/

相关文章:

java - SQL 更新列从一个表到另一个

node.js - 在 NodeJS 中获取所有 Linux 系统服务的最佳方式?

java - Context.startForegroundService() 然后没有调用 Service.Foreground

c# - 在 ASP.NET MVC 中管理用户的最佳方式是什么

c# - 插入语句中的错误 C#/MySQL 多个选择语句

c# - 在 Visual Studio 2015 RC 中使用 intelliTest 记录每个运行的测试场景

windows - 如何让 Windows SCM 在失败时重新启动我的服务

c# - 并行 Foreach 和操作

mysql - 创建查询以显示长文本字段中特定结果的计数

sql - 条件连接不同的表