Thursday, March 7, 2019

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


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


Recently I encountered the above exception when I tried to create object of entity type eg, Project and tried to map only those columns which will be used in mapping of entity to business or DTO object. For performance point of view, instead of pulling of all columns of entity, I wanted to included only those columns which will be used in mapping of entity to business object.

Here is EF Query:

List projects = _db.Projects.Select(x = > new Project { Name = x.Name, Location = x.Location }).ToList();


To resolve this problem, you have two option, either you can first map the entity column to an anonymous type or direct maps to Business object.


Maps to anonymous type:

In below EF query, First Project entity is being mapped to anonymous type then call to ToList() to populate data into location memory object and again maps to Project entity object.


C# EF Query:


List projects = _db.Projects.Select(x = > new { Name = x.Name, Location = x.Location }).ToList();


Maps to Business object:

In below code, Project entity directly maps to Business object (ProjectData).


C# EF Query:


List projects = _db.Projects.Select(x = > new ProjectData {  Name = x.Name, Location = x.Location }).ToList();

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...