I am leveraging EF Core
and using .Include
to get data from two tables by using some filters. Here, I have a filter which requires to query on child table (the one I am getting from .Include
) and I am not sure how to do that.
As shown below: my filters are, location, stockNumber, exceptionType, supplierName
where I want to run my query for supplier
but, not sure how to do that.
Table Design:
public class Operation
{
[Key]
public int OperationId { get; set; }
[Required, MaxLength(10), Unicode(false)]
public string Location { get; set; }
[Required]
public long StockNumber { get; set; }
[Required, MaxLength(17), Column(TypeName = "char(17)")]
public string Vin { get; set; }
public decimal TotalCarliCost { get; set; }
public decimal TotalCostSubmitted { get; set; }
public DateTimeOffset? EarliestPaymentDate { get; set; }
public bool? HasPartLineItems { get; set; }
public bool? HasSubletItems { get; set; }
[Required]
public List<SupplierByOperation> Suppliers { get; set; }
}
public class SupplierByOperation
{
[Key]
public int SupplierByOperationId { get; set; }
[Required]
public long StockNumber { get; set; }
[Required, MaxLength(500), Unicode(false)]
public string SupplierName { get; set; }
public bool? TiedToPart { get; set; }
public bool? TiedToSublet { get; set; }
public int OperationId { get; set; }
}
Repo.cs
private IQueryable<Operation> GenerateBaseQuery(string location, string stockNumber = "",
string exceptionType = "", string supplierName = "")
{
var query = _dbContext.Operation.AsNoTracking()
.Include(x => x.Suppliers)
.Where(_ => _.Location.Equals(location));
if (string.IsNullOrWhiteSpace(stockNumber)) return query;
var convertedStockNumber = long.Parse(stockNumber);
query = query.Where(e => e.StockNumber.Equals(convertedStockNumber));
if (string.IsNullOrWhiteSpace(exceptionType)) return query;
query = exceptionType.ToLower() switch
{
// TODO: use constants
"parts" => query.Where(e => e.HasPartLineItems.Equals(true)),
"sublets" => query.Where(e => e.HasSubletItems.Equals(true)),
"all" => query.Where(e => e.HasPartLineItems.Equals(true) && e.HasSubletItems.Equals(true)),
_ => query
};
// Following throws these 2 errors
// Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<SupplierByOperation>' to 'bool'
// Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
if (string.IsNullOrWhiteSpace(supplierName)) return query;
query = query.Where(o => o.Suppliers.Where(s => s.SupplierName == supplierName));
return query;
}