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

Posted by Sheonarayan under Error and Solution on 3/12/2015 | Points: 10 | Views : 5771 | Status : [Administrator] | Replies : 0

I was getting below error when I was trying to populate the ViewModel by joining two Models in my ASP.NET MVC project.

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

To fix this error, we need to populate the Joined data into Anonymous type and then from that collection to the Viewmodel.

var list = (from p in db.PersonalDetails
join f in db.Files
on p.AutoId equals f.PersonalDetailsId
select new
{
Active = p.Active,
Age = p.Age,
AutoId = p.AutoId,
FileName = f.FileName,
FirstName = p.FirstName,
LastName = p.LastName
}).ToList()
.Select(x => new PersonaldetailsFilesViewModel()
{
Active = x.Active,
Age = x.Age,
AutoId = x.AutoId,
FileName = x.FileName,
FirstName = x.FirstName,
LastName = x.LastName
});


Look at the first set the select keyword that is selecting properties from both PersonalDetails and Files connection and populating to Anonymous type and then again selecting from that List collection and populating into PersonaldetailsFilesViewModel object.

Hope this will help someone.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com



Responses

(No response found.)

Login to post response