EF query cannot return complex type

Another error you can recieve from the Entity Framework is the following:
The entity or complex type <complex type> cannot be constructed in a LINQ to Entities query

Here is the query that I used and didn’t work:

List<ProcessDefinition> entries = (from PD in contextCommon.ProcessDefinitions
where PD.Process.SourceSystem == sourceSystem && PD.Process.MessageType == messageType && PD.Process.ResolveProcess == true
select new ProcessDefinition { ProcessId=PD.ProcessId, StepId=PD.StepId, Sequence=PD.Sequence,
Status =PD.Status, Notification=PD.Notification, IsLastStep=PD.IsLastStep }).ToList<ProcessDefinition>();

And here is the query that didn’t return an error:

List<ProcessDefinition> entries = (from PD in contextCommon.ProcessDefinitions
where PD.Process.SourceSystem == sourceSystem && PD.Process.MessageType == messageType && PD.Process.ResolveProcess == true
select PD).ToList<ProcessDefinition>();

The difference between the two queries is that I didn’t make a custom selection in the second query. You can do that if you return an anonymous type like var. The other option is that you create a custom object, let’s say CustomProcessDefinition and only include the fields in this class that you want to select.

Below is an example where I first create a class ProductDTO and then make a custom selection:

public class ProductDTO
{
public string Name { get; set; }
// Other field you may need from the Product entity
}
And your method will return a List of DTO’s.

public List<ProductDTO> GetProducts(int categoryID)
{
return (from p in db.Products
where p.CategoryID == categoryID
select new ProductDTO { Name = p.Name }).ToList();
}

Reasoning: Mapped entities in EF basically represent database tables. If you project your custom selection onto a mapped entity, you basically load an entity which is not in a valid state.

Leave a Reply

Your email address will not be published. Required fields are marked *