I am using EF 4 with repository pattern which has the generic query method shown below:
public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
{
return objectSet.Where(filter);
}
I know I can select a complete object like this:
context.PeriodRepository.Query(a => a.EntityId == selectedEntityId);
But I want to pass a Linq query that returns it as type instead of IEnumerable<type> using a LINQ expression without changing the method. Please advise me how to do that.
A Query describes the operations performed on the list; you must perform the query to get the result(s).
Using
.ToList()/.ToArray()will return all items that match the query. Use.First()to get the first item that matches or.FirstOrDefault()to get the first item or the default value for no matches.The default value for a class is
null.I think your code should be like this:
Also note that,
First()will throw an exception when there is no match.