首页 > 解决方案 > 从特定日期时间从 db 获取所有记录

问题描述

我有一个查询,用于从用户在客户端页面上输入的特定日期从数据库中检索所有记录。

目标是当用户在客户端输入日期时,服务器必须从特定日期和未来检索所有数据(从 RentPeriod 表中)。

我的代码如下所示:

  DateTime realStartTime = Convert.ToDateTime(startTime);                      
                   var parkingspot = from Address in _parkShareDbContext.Addresses.Where(a => a.Active == true)
                   join ParkingSpot in _parkShareDbContext.ParkingSpots.Where(p => p.Active == true).Where(p => size == null || p.Spotsize == size) on Address.Id equals ParkingSpot.Address.Id
                   join RentPeriod in _parkShareDbContext.RentPeriods.Where(rp => rp.Type == periodType && rp.IsRentedOut == false).Where(rp => realStartTime >= rp.RentPeriodStart) on ParkingSpot.Id equals RentPeriod.ParkingSpotId

提前致谢。

标签: c#linq

解决方案


您需要使用 select 子句结束查询 - 我认为您的租期开始时间比较是错误的,除非我误解了您 - 但我也会将您的整个查询转换为查询语法而不是混合您有,例如

var parkingspot = from Address in _parkShareDbContext.Addresses
                  join ParkingSpot in _parkShareDbContext.ParkingSpots on Address.Id equals ParkingSpot.Address.Id
                  join RentPeriod in _parkShareDbContext.RentPeriods on ParkingSpot.Id equals RentPeriod.ParkingSpotId
                  where ParkingSpot.Active 
                  && (size == null || ParkingSpot.Spotsize == size)
                  && RentPeriod.Type == periodType
                  && !RentPeriod.IsRentedOut
                  && RentPeriod.RentPeriodStart >= realStartTime
                  select RentPeriod;

编辑

但是,根据上面的评论,对于像这样的复杂查询,您通常最好编写参数化 SQL 查询,或使用存储过程来获取数据。

我也不确定你为什么需要Address在那里?


推荐阅读