Mapping fields from multiple tables to model in MVC entity framework

Matt 1 Reputation point
2021-07-09T10:41:12.88+00:00

Hi,

I'm trying to map fields from two tables to a model but I keep getting the following error;

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

Here is my code. Can anyone tell me what I'm doing wrong please?

[HttpGet, Authorize]
public ActionResult GetAssetTypeChecks(bool? isActive = null)
{
try
{
// List<AssetTypeCheck> assetTypeCheck = CompanyDatabase.AssetTypeChecks.AsNoTracking().OrderBy(x => x.Id).ToList();

            List<AssetTypeCheck> assetTypeCheck = (from app in CompanyDatabase.AssetTypeChecks
                     join assettype in CompanyDatabase.AssetTypes on app.AssetTypeId equals assettype.Id
                     select new AssetTypeCheck
                     {
                         Id = app.Id,
                         Name = app.Name,
                        CheckType = app.CheckType,
                        Description = app.Description,
                         OrderNum = app.OrderNum
                    }).ToList();


            return Json(new { success = true, result = assetTypeCheck }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception exception)
        {
            return Json(new { success = false, message = exception.Message }, JsonRequestBehavior.AllowGet);
        }
    }
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,096 Reputation points
    2021-07-12T08:29:14.143+00:00

    Hi @Matt ,
    As far as I think,you cannot (and should not be able to) project onto a mapped entity. The project could onto an anonymous type: IEnumerable<> or onto a DTO.
    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.