这是我的DB(其中的一部分):
Vehicule table :
Matv string primary ;
cCode int foreign key references city,
// some other columns
Indisponible(unavailable) table:
idin int primary,
from date
to date
idv string foreign key references Matv in vehicule table.
一辆车可能有很多不可用的日期。
这是我的搜索方法:
public ActionResult search(int citycode, string from, string to)
{
DateTime dd1 = Convert.ToDateTime(from);
DateTime df1 = Convert.ToDateTime(to);
var model = (from p in entity.vehicule
join y in entity.indisponible on p.Matv equals y.idv
where p.cCode == citycode && ( dd1 > y.Df && df1 < y.Dd )
select p).ToList();
return View(model);
}
此搜索查询可让我查找城市中所有可用的汽车,日期为from
和to
。
所以要做到这一点,我必须检查用户选择的日期不在不可用的表中。
例如,这辆车是不可用的
从01/04/201至2012年4月26日以及2012年5月1日至2012年5月9日。
因此,如果用户搜索从2012年4月28日到2012年4月30日,则必须显示此车 否则,如果他搜索从2012年4月28日到2012年5月3日,这辆车将不会显示在搜索结果中。
但是出了点问题,它从未显示出任何结果。有人可以帮我解决吗?
答案 0 :(得分:2)
我将在黑暗中拍摄:Df
是指“Date Fin”,Dd
是指“Date Debut”?如果是这样,您的查询就会查找在日期范围的开头和之前结束的项目。
你可能想要这样的东西:
dd1 < y.Df && df1 > y.Dd
如果您只想包含超出给定范围的日期,则需要在结束日期之后或之前 的日期:
dd1 > y.Df || df1 < y.Dd
答案 1 :(得分:1)
where
适用于每一行。它不能同时考虑多行来确定可用性。但它应该......在我们的范围内任何不可评论的记录应该完全过滤汽车。
这可能更接近你想要的东西:
from p in entity.vehicule
where p.cCode == citycode
where p.indisponibles.All(y => y.Df < dd1 || df1 < y.Dd)
select p
如果每条记录都满足该条件,则返回true;如果源为空,则返回true。
如果在我们的范围之后开始或者如果它在我们的范围之前结束,那么不可分辨的记录不应该过滤我们的车。如果所有不可分辨的记录都是这样,那么我们就保留这辆车。
答案 2 :(得分:1)
以这种方式解决:
from p in entity.vehicule
where p.agence.idgov == idv
where !p.indisponible.Any(b => (dd1 >= b.Dd && dd1 <= b.Df) || (df1 >= b.Dd && df1 <= b.Df))
where !p.indisponible.Any(c => (c.Dd >= dd1 && c.Dd <= df1) || (c.Df >= dd1 && c.Df <= df1))
select p).ToList();
感谢大家的帮助。