Union in entity framework

.net c# entity-framework linq-to-entities

Question

I have two tables: Vehicles and Workers.

Vehicle(Id, Number)
Workers(Id, Name, ContractorVehicleNumber)

I would like to write lambda query to return all the vehicles and the contractor vehicles. Something like in sql:

SELECT Id, Number
FROM Vehicle
UNION
SELECT NULL, ContractorVehicleNumber
FROM Workers

This is what I made:

public IQueryable<Vehicle> Get(bool includeContractorVehicles)
{
    IQueryable<Vehicle> query = GetQuery();

    if (includeContractorVehicles == true)
    {
        WorkerRepository rep = new WorkerRepository();
        IQueryable<Vehicle> contractorsVehicles = rep.GetWirkers().
            Select(x => new Vehicle()
            {
                VehicleNumber = x.ContractorVehicleNumber
            });
        query = query.Union(contractorsVehicles);
    }

    return query;
}  

But I get an exception:

The entity or complex type 'XXXXXXXX' cannot be constructed in a LINQ to Entities query.

1
16
1/21/2015 12:47:26 AM

Accepted Answer

You cannot construct mapped entity type in projection. Your former example will work only if you create a new special type used for projection:

public class VehicleResult
{
    public string Number { get; set; }
    ... // If you don't need more then one column you can use simple type instead of custom class
}

And your method will look like:

public IQueryable<VehicleResult> Get(bool includeContractorVehicles)
{
    IQueryable<VehicleResult> query = GetQuery().Select(v => new VehicleResult { ... });

    if (includeContractorVehicles == true)
    {
        WorkerRepository rep = new WorkerRepository();
        IQueryable<VehicleResult> contractorsVehicles = rep.GetWorkers().
            Select(x => new VehicleResult()
            {
                Number = x.ContractorVehicleNumber
            });
        query = query.Union(contractorsVehicles);
    }

    return query;
}  
15
4/9/2018 1:42:42 AM

Popular Answer

You cant create entities in the select statement. Try this instead:

public class VehicleDTO
{
  public int Id { get; set; }
  public int Number { get; set; }
} 

public IQueryable<VehicleDTO> Get(bool includeContractorVehicles)
{
    var query = GetQuery().Select(x => new VehicleDTO(){ ID = c.ID, Number = c.Number });

    if (includeContractorVehicles)
    {
        WorkerRepository rep = new WorkerRepository();
        var contractorsVehicles = rep.GetWirkers().
            Select(x => new VehicleDTO(){ Number = x.ContractorVehicleNumber});
        query = query.Union(contractorsVehicles);
    }

    return query;
} 

Also are you sure you want a Union and not a Concat ?



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow