C# - .Select() 内的动态谓词抛出期望

问题描述 投票:0回答:1

我有下一个领域模型:

public class UserTask
{
    public int Id { get; set; }
    public string Name { get; set; }
    // ...
    public virtual ICollection<TaskHistory> TaskHistories { get; set; } = new List<TaskHistory>();
}

public class TaskHistory
{
    public int Id { get; set; }
    public int UserTaskId { get; set; }
    public string Name { get; set; }
    // ...
    public virtual UserTask UserTask { get; set; } = new List<UserTask>();
}

然后在业务逻辑中我想使用动态动态谓词。但我在执行中遇到了问题。业务逻辑接下来的方向:

...
Expression<Func<UserTask, bool>> taskPredicate = (t => t.Name == "ABC");
Func<TaskHistory, bool> taskHistoryPredicate = (th => th.Name == "ABC");

queryable = (IOrderedQueryable<UserTask>)context.UserTasks.
        .Include(t => t.TaskHistories)
        .Where(taskPredicate)
        .Select(t => new UserTask()
        {
            Id = t.Id,
            Name = p.Name,
            // other properties...
            TaskHistories = (ICollection<TaskHistory>) t.TaskHistories.Where(taskHistoryPredicate) // <- this doesn't work
            //TaskHistories = (ICollection<TaskHistory>) t.TaskHistories.Where(th => th.Name == "ABC") // <- this works
        });
        
List<UserTasks> tasks = queryable.ToList();
...

在转换为列表时会抛出异常:

System.ArgumentException:'类型'System.Func

2[TestPredicate.TaskHistory,System.Boolean]' cannot be used for parameter of type 'System.Linq.Expressions.Expression
1的表达式[System.Func
2[TestPredicate.TaskHistory,System.Boolean]]' of method 'System.Linq.IQueryable
1[TestPredicate.TaskHistory]其中[TaskHistory](System.Linq.IQueryable
1[TestPredicate.TaskHistory], System.Linq.Expressions.Expression
1[System.Func`2 [TestPredicate.TaskHistory,System.Boolean]])'(参数'arg1')

我无法理解为什么当我使用硬编码谓词时它可以工作,但是当我从变量插入它时却不能。我也尝试将

Func<,>
更改为
Expression<Func<,>>
并执行
taskHistoryPredicate.Compile()
,同样的错误。

c# linq entity-framework-core predicate
1个回答
0
投票

你必须改变

Func<TaskHistory, bool> taskHistoryPredicate = (th => th.Name == "ABC");

Expression<Func<TaskHistory, bool>> taskHistoryPredicate = (th => th.Name == "ABC");
© www.soinside.com 2019 - 2024. All rights reserved.