Search code examples
sqllinqexplicitconstruction

How to specify which columns can be returned from linq to sql query


I'm trying to only return a few columns from a linq to sql query but if I do, it throws the exception:

Explicit construction of entity type 'InVision.Data.Employee' in query is not allowed

Here's the code:

return db.Employees.Select(e => new Employee()
       { EmployeeID = e.EmployeeID, FirstName = e.FirstName,
         LastName = e.LastName }).ToList();

If I return everything then it will throw exceptions about circular references because it needs to be serialized to be used in javascript, so I really need to limit the columns... Thanks for any tips you can give me to solve this.


Solution

  • Basically, if you just want the columns, select those. If you want the employee entity, select it. There's not much of a middle ground here. I recommend against creating a new class just for this. Yuck!

    Do this:

    return db.Employees
       .Select(e => new { e.EmployeeID, e.FirstName, e.LastName })
       .ToList();