Dynamically querying 2 entity types and mapping results back into specific entity set

c# dapper entity-framework linq

Question

We have tables in our database which are normalized in the sense that the one should inherit fields from the other.

So, for example:

'Vehicle' fields:
 - SpecificType
 - SerialNumber

'Car' fields:
 - FuelType

'Boat' fields:
 - HullSize

If the user searched on SerialNumber and FuelType, I know I need to return a Car, but I don't want to execute the search in two steps:

 1. List<Vehicles> SearchVehicles( serialNumber )
 2. List<Cars> SearchCars(List<Vehicles>, FuelType) // From the list of Vehicles, query all Cars with specified FuelType

Is there a way to write a generic method using Linq that could give me the desired result?

I looked at the Dapper framework as a means of dynamically building criteria, but I'm not sure if there's a better way (practice), and I'd like to see what other options there are.

Popular Answer

I hope this can help you

To search all cars by fueltype, use:

private static List<Car> SearchCars(List<Vehicle> vehicles, FuelType fueltype)
{
   return vehicles.Where(f =>f is Car && (f as Car).FuelType == fueltype) 
          .Select(x => (Car)x).ToList();
}

If you want also filter by SerialNumber Use:

private static List<Car> SearchCars(List<Vehicle> vehicles, FuelType fueltype,          string serialnumber)
 {
   return vehicles.Where(f =>f.SerialNumber==serialnumber && f is Car 
                         && (f as Car).FuelType == fueltype)
                  .Select(x => (Car)x).ToList();
 }



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why