public List<VehicleOnTaskDetailDto> GetVehicleOnTaskDetailFinished(VotFilterRequest filterRequest)
{
using VehicleDeliveryContext context = new VehicleDeliveryContext();
var result = (from v in context.VehiclesOnTask
join d in context.Departments on v.DepartmentId equals d.Id
join dr in context.Drivers on v.DriverId equals dr.Id
join vehicle in context.Vehicles on v.VehicleId equals vehicle.Id
where v.IsDeleted != true
where v.IsFinished == true
orderby v.GivenDate descending
select new VehicleOnTaskDetailDto{
VehicleOnTaskId = v.Id,
VehiclePlate = vehicle.Plate,
VehicleId = v.VehicleId,
DriverName = $"{dr.Name} {dr.Surname} - {dr.Mission}",
DepartmentName = d.Name,
TaskDefinition = v.TaskDefinition,
AuthorizedPerson = v.AuthorizedPerson,
Address = v.Address,
GivenDate = v.GivenDate,
ReturnDate = v.ReturnDate
}).ToList();
return result;
}
我想根据VotFilterRequest自带的DateType过滤器添加2行代码,类似如下所示:
if (filterRequest.DateType == "GivenDate")
{
where filterRequest.FirstDate <= v.GivenDate
where filterRequest.LastDate >= v.GivenDate
}
else
{
where filterRequest.FirstDate <= v.ReturnDate
where filterRequest.LastDate >= v.ReturnDate
}
我知道你不能这样做,但我也不想重复我的代码。有什么办法可以很快做到这一点吗?谢谢您的问候。
您可以通过使用 LINQ 扩展方法并在构建查询期间使用
IQueryable
轻松实现它:
var query = context.VehiclesOnTask
// You'd need to define those navigation properties.
.Include(x => x.Department)
.Include(x => x.Driver)
.Include(x => x.Vehicle)
.Where(x => x.IsDeleted == false)
.Where(x => x.IsFinished == true);
query = filterRequest.DateType == "GivenDate"
? query.Where(v => filterRequest.FirstDate <= v.GivenDate && filterRequest.LastDate >= v.GivenDate)
: query.Where(v => filterRequest.FirstDate <= v.ReturnDate && filterRequest.LastDate >= v.ReturnDate);
return query
.OrderByDescending(x => x.GivenDate)
.Select(v => new VehicleOnTaskDetailDto
{
VehicleOnTaskId = v.Id,
VehiclePlate = vehicle.Plate,
VehicleId = v.VehicleId,
DriverName = $"{dr.Name} {dr.Surname} - {dr.Mission}",
DepartmentName = d.Name,
TaskDefinition = v.TaskDefinition,
AuthorizedPerson = v.AuthorizedPerson,
Address = v.Address,
GivenDate = v.GivenDate,
ReturnDate = v.ReturnDate,
})
.ToList();