Reputation: 2777
I have problem with Func delegate in LINQ expression. This is the problematic part of the method (repository.Items is IQueryable<T>)
:
public static ActionResult XXX<T>(IRepository<T> repository,
Func<T, int> keyExtractor, int id = 0)
{
if (id == 0) return ...
T item = repository.Items.Where(x => keyExtractor(x) == id).
FirstOrDefault();
if (item == null) return ...
try {
repository.DeleteItem(item);
return ...
} catch (Exception e) {
return ...
}
}
But when i run the method, i get error like type of node is not supported in LINQ entities. I tried also version with predikate but i had no luck at all.
Any ideas how to fix it?
I find out one possible way. LINQ performs delayed execution so i must first enforce execution like this:
T item = repository.Items.AsEnumerable().Where(x => keyExtractor(x) == id)
Upvotes: 2
Views: 2757
Reputation: 60493
If you want to work on a IQueryable<T>
, your argument must be an Expression<Func<T, int>>
, not a Func<T, int>
.
Func<T, int>
will work with an IEnumerable<T>
.
Where
extensions methods has the same name for IQueryable<T>
and IEnumerable<T>
, but not the same arguments...
(by the way you could write repository.Items.FirstOrDefault(x => keyExtractor(x) == id)
;
Upvotes: 5