Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I try query with linq but I get the following error:
The entity or complex type 'SELEXExpressCL.Data.TRUCK' cannot be constructed in a LINQ to Entities query.

TRUCK truck = (from item in context.TRUCKS
               where item.NUMBER == TruckNo
               select new TRUCK()
               {
                   TRUCK_ID = item.TRUCK_ID,
                   NUMBER = item.NUMBER,
                   MAKE_TYPE = item.MAKE_TYPE,
                   MODEL = item.MODEL,
                   YEAR = item.YEAR,
                   VIN = item.VIN,
                   PLATE_NO = item.PLATE_NO,
                   COLOR = item.COLOR,
                   CODE = item.CODE,
                   MC_NUMBER = item.MC_NUMBER,
                   ANNUAL_INSPECTION = item.ANNUAL_INSPECTION,
                   INVESTOR_ID = item.INVESTOR_ID,
                   IsAVAILABLE = item.IsAVAILABLE,
                   STATUS_ID = item.STATUS_ID

               }).Single();


What I have tried:

I don't want to use the statement forech:

var query = from a in context.TRUCKS
                        where a.NUMBER == TruckNo
                        select a;

TRUCK TruckObj = new TRUCK();

foreach (var item in query)
{
    TruckObj.TRUCK_ID = item.TRUCK_ID;
    TruckObj.NUMBER = item.NUMBER;
    TruckObj.MAKE_TYPE = item.MAKE_TYPE;
    TruckObj.MODEL = item.MODEL;
    TruckObj.YEAR = item.YEAR;
    TruckObj.VIN = item.VIN;
    TruckObj.PLATE_NO = item.PLATE_NO;
    TruckObj.COLOR = item.COLOR;
    TruckObj.CODE = item.CODE;
    TruckObj.MC_NUMBER = item.MC_NUMBER;
    TruckObj.ANNUAL_INSPECTION = item.ANNUAL_INSPECTION;
    TruckObj.INVESTOR_ID = item.INVESTOR_ID;
    TruckObj.IsAVAILABLE = item.IsAVAILABLE;
    TruckObj.STATUS_ID = item.STATUS_ID;
}
Posted
Updated 26-Feb-18 23:37pm

1 solution

You don't have to create a new TRUCK class, you already have the object you need in "item" so just select that

TRUCK truck = (from item in context.TRUCKS
               where item.NUMBER == TruckNo
               select item).Single();


BTW I googled the error message and this was the first result

c# - The entity cannot be constructed in a LINQ to Entities query - Stack Overflow[^]

It's much quicker for you to do basic research before asking a question as you can often find the answer yourself.

Also consider SingleOrDefault rather than Single in case there is an issue with your data.
 
Share this answer
 
Comments
phil.o 27-Feb-18 6:07am    
5'd

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900