I'm trying to use the entity framework to filter my GET method... Using the if the condition it's working
public async Task<List<TimeEntryViewModel>> Get(TimeEntryFilter filter)
{
var result = await _readRepository
.FindByCondition(x => x.IsApproved == true)
.Include(x => x.Task)
.Include(x => x.Account)
.Select(x => new TimeEntryViewModel
{
AccountName = x.Account.Name,
Date = x.Date,
StartTime = x.StartTime,
FinishTime = x.FinishTime,
InternalId = x.InternalId,
TaskId = x.TaskId,
TaskName = x.Task.Name,
CreatedBy = x.CreatedBy,
CustomerName = x.Task.Project.ServiceOrder.Customer.Name
}).ToListAsync().ConfigureAwait(false);
if (filter.AccountName != null ||
(filter.StartDate.HasValue && filter.FinishDate.HasValue && (filter.StartDate <= filter.FinishDate)) ||
(filter.TaskName != null) ||
(filter.CustomerName != null) ||
(filter.InternalId != null))
result = result.Where(x =>
(x.AccountName.ToString().Contains(filter.AccountName)) &&
(x.Date >= filter.StartDate && x.Date <= filter.FinishDate) &&
(x.CustomerName.ToString().Contains(filter.CustomerName)) &&
(x.TaskName.ToString().Contains(filter.TaskName)) &&
(x.InternalId.ToString().Contains(filter.InternalId.ToString()))).ToList();
return result;
}
But I imagine that there is a way to improve this method without using if
I'd had already tried to do that (Just filter account name to show) But returned Internal Server Error
var result = await _readRepository
.FindByCondition(x => x.IsApproved == true)
.Where(x => string.IsNullOrEmpty(filter.AccountName) || x.Account.Name.ToString().Contains(filter.AccountName))
.Include(x => x.Task)
.Include(x => x.Account)
.Select(x => new TimeEntryViewModel
{
Id = x.Id,
AccountName = x.Account.Name,
Date = x.Date,
Description = x.Description,
StartTime = x.StartTime,
FinishTime = x.FinishTime,
InternalId = x.InternalId,
OnSite = x.OnSite,
IsApproved = x.IsApproved,
IsBillable = x.IsBillable,
TaskId = x.TaskId,
TaskName = x.Task.Name,
CreatedBy = x.CreatedBy,
CustomerName = x.Task.Project.ServiceOrder.Customer.Name
}).ToListAsync().ConfigureAwait(false);
Okay Guys EDIT1: In my second sample, using InternalId instead of Account.Name
.Where(x => (string.IsNullOrEmpty(filter.InternalId.ToString())) || x.InternalId.ToString().Contains(filter.InternalId.ToString()))
it worked.... I believe that I'm having trouble to work with something that is a foreign key in my table...