Search code examples
linqentity-frameworkreturn-valueprojectionentities

Linq to Entities - Project into object, search on all fields but only return ONE single property


I'm curious if there is a way when using Linq to Entities to project into a new object, add .Where extensions to the initial Linq query (deferred execution and some building of dynamic lambda expressions) to further filter the query based on the properties of the projected object but (and here is the main question) ONLY return ONE property (say an ID field) from the database (the select statement generated only has one return value).

So I want to change the following:

        employees = from e in context.Employee
                    select new EmployeeObject()
                    {
                            EmployeeId = e.EmployeeId,
                            EmployeeFirstName = e.FirstName,
                             EmployeeLastName = e.LastName
                    };

So that I can append employees with .Where extensions with lambdas to further narrow the search but only return EmployeeId and have the SQL that is generated reflect that.

I'm still in the process of learning Linq to Entities so please forgive me if I did not describe something properly.

Thank you!


Solution

  • You can do this:

    var employeeIds = from e in context.Employee
                      select new {
                          EmployeeID = e.EmployeeId
                      };
    

    It will only return the one property you need via an anonymous type. Or alternatively:

    var employeeIds = context.Employee.Where(/*filters...*/).Select(e => e.EmployeeId);
    // another alternative: 
    var employeeIds = from e in context.Employee select e.EmployeeId;
    

    That will give you just the Ids.

    EDIT:
    As long as you don't enumerate over the query, the query is not executed.
    So if you say

    var query = context.Employee;
    

    you have a very simple query that you can decorate with additional clauses as much as you like:

    query = query.Where(e => e.LastName.StartsWith("S"));
    query = query.Where(e => e.FirstName == "Blah");
    

    All those additions are not executing the query, so as long as your ObjectContext is valid, you can refine your query like that.

    When you're done adding the clauses, you can add the final projection

    var results = query.Select(e => e.EmployeeId);
    

    and only then you should enumerate over results or use it somewhere. Of course you can only add the projection after you have performed your filtering, because per definition the projection just drops all properties other than EmployeeId.