Can I make my EF objects retrieve only specific columns in the sql executed? If I am executing the below code to retrieve objects, is there something I can do to only get c
Sure. Projection does this:
var q = from r in Context.TableName
select new
{
Id = r.Id,
Status = r.Status
}
Here's an actual example (obviously, my DB has different tables than yours). I added my EF model to LINQPad and typed the following query:
from at in AddressTypes
select new
{
Id = at.Id,
Code = at.Code
}
LINQPad shows me that the generated SQL is:
SELECT
1 AS [C1],
[Extent1].[AddressTypeId] AS [AddressTypeId],
[Extent1].[Code] AS [Code]
FROM
[dbo].[AddressType] AS [Extent1]
None of the other fields from the table are included.
Responding to updated question
Your columns
argument says it takes a type T and returns the same type. Therefore, the expression you pass must conform to this, or you need to change the type of the argument, i.e.:
public IEnumerable<U> GetBy<U>(Expression<Func<T, bool>> exp, Expression<Func<T, U>> columns)
{
return Table.Where<T>(exp).Select<T, U>(columns);
}
Now the expression can return any type you care to use.