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:
Post a Comment