C#:返回符合条件的任何项目

时间:2015-03-06 18:36:05

标签: c# asp.net sql-server linq asp.net-mvc-5

我有这样的方法:

    public ActionResult ShowAvailableSpots(int Id, DateTime ArrivalDate, DateTime LeaveDate)
    {
        var query2 = db.Spots
            .Where(c => db.Reservations.Any(r =>
                           DbFunctions.TruncateTime(ArrivalDate) <= DbFunctions.TruncateTime(r.ArrivalDate) && DbFunctions.TruncateTime(LeaveDate) <= DbFunctions.TruncateTime(r.ArrivalDate)
                        || DbFunctions.TruncateTime(ArrivalDate) >= DbFunctions.TruncateTime(r.LeaveDate)
            )).ToList();

        ViewBag.StartingDate = ArrivalDate;
        ViewBag.EndingDate = LeaveDate;
        ViewBag.AvailableSpots = query2;

        ViewBag.CampingSpotId = new SelectList(query2, "CampingSpotId", "SpotName");

        return View();
    }

确定任何预订是否符合日期标准。如果它们不匹配,则返回带有Campingspots的列表。

问题是,它返回所有斑点或无斑点,而不仅仅是可用斑点。这是由.Any方法引起的。如何过滤掉不可用的露营地?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

var query2 = db.Spots.Where(c => db.Reservations
                                   .Where(r => c.CampingSpotId == r.CampingSpotId)
                                   .All(r => DbFunctions.TruncateTime(LeaveDate) <= DbFunctions.TruncateTime(r.ArrivalDate)
                                          || DbFunctions.TruncateTime(ArrivalDate) >= DbFunctions.TruncateTime(r.LeaveDate))
                   )).ToList();

内部Where声明说我们只检查适用于该露营地的预订,并且All声明检查以确保该露营地的每个预订都在我们的窗口之外对此很感兴趣。