简体   繁体   English

LINQ表达式中的Func参数

[英]Func parameter in LINQ expression

I have problem with Func delegate in LINQ expression. 我在LINQ表达式中遇到Func委托问题。 This is the problematic part of the method (repository.Items is IQueryable<T>) : 这是方法中存在问题的部分(repository.Items是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. 但是当我运行该方法时,我得到的错误就像LINQ实体中不支持节点类型一样。 I tried also version with predikate but i had no luck at all. 我也尝试使用predikate版本,但我根本没有运气。

Any ideas how to fix it? 任何想法如何解决它?

I find out one possible way. 我找到了一种可行的方法。 LINQ performs delayed execution so i must first enforce execution like this: LINQ执行延迟执行,所以我必须首先执行这样的执行:

T item = repository.Items.AsEnumerable().Where(x => keyExtractor(x) == id)

If you want to work on a IQueryable<T> , your argument must be an Expression<Func<T, int>> , not a Func<T, int> . 如果要处理IQueryable<T> ,则参数必须是Expression<Func<T, int>> ,而不是Func<T, int>

Func<T, int> will work with an IEnumerable<T> . Func<T, int>将与IEnumerable<T>

Where extensions methods has the same name for IQueryable<T> and IEnumerable<T> , but not the same arguments... Where扩展方法与IQueryable<T>IEnumerable<T>具有相同的名称,但不是相同的参数...

(by the way you could write repository.Items.FirstOrDefault(x => keyExtractor(x) == id) ; (顺便说一句,你可以编写repository.Items.FirstOrDefault(x => keyExtractor(x) == id) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM