moi*_*key 4 c# linq asp.net datetime entity-framework
我目前正在开展一些工作,要求我检查两个日期之间的可用性.我目前的方法没有返回预期的结果.例如,假设我有以下保留意见:
我希望查看2015年4月15日至2015年4月16日期间的所有预订.在视觉上,这可能看起来像:
15 16
X________|_____|______X
|X____|_____________X
X______________|____X|
| |
Run Code Online (Sandbox Code Playgroud)
要获得我在使用的这些日期之间的所有预订:
public List<ReservationClientModel> GetReservationsByDateRange(int id, DateTime checkin, DateTime checkout)
{
var reservation = _repository.FindAllBy(x =>
(x.StartDate >= checkin && x.EndDate <= checkout) ||
(x.StartDate >= checkin && x.StartDate <= checkout) ||
(x.EndDate >= checkin && x.EndDate <= checkout)),
y => y.RoomTypeNav)
.ToList();
return Mapper.Map<List<ReservationClientModel>>(reservation);
}
Run Code Online (Sandbox Code Playgroud)
哪个使用:
public IEnumerable<TEntity> FindAllBy(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includes)
{
var set = _dbSet.AsQueryable();
set = includes.Aggregate(set, (current, include) => current.Include(include));
return set.Where(predicate);
}
Run Code Online (Sandbox Code Playgroud)
这只会返回最后两项保留,虽然,我认为这是因为它是检查>=和<=对日期,而不是检查它在上述范围内.我知道使用SQL BETWEEN运算符,但我想知道是否有任何方法可以使用Linq表达式或在C#中执行此操作?理想情况下,我想将此作为EF Query的一部分执行,而不是返回所有预留,然后在此列表上执行操作.
谢谢.
如果遵循以下规则,则两个范围重叠:
(StartDate1 <= EndDate2) and (EndDate1 >= StartDate2)
Run Code Online (Sandbox Code Playgroud)
通过将此规则应用于您的代码,您将获得:
var reservation = _repository
.FindAllBy(x => x.StartDate <= checkout && x.EndDate >= checkin,
y => y.RoomTypeNav)
.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4021 次 |
| 最近记录: |