我的问题与这个问题有关:linq-expression-with-generic-class-properties
这次我想要获取具有相同id的新创建对象。id实际上是外键,因此可以有不同的名称。
我想出了以下方法:
public static IEnumerable<T> GetNew<TId, T>(IQueryable<T> objects, TId id, DateTime date, Expression<Func<T, TId>> idSelector)
where T : class, ISyncable<TId>
{
return objects.Where(o => idSelector(o) == id && o.CreatedDate > date);
}
该方法将会被这样调用:
var modified = GetNew(dbObjects, id, date, entity => entity.PersonId);
很不幸,我遇到了错误:
'idSelector' is a variable but is used like a method.
传递给该方法的表达式应该做到这样:
objects.Where(o => o.PersonId == id && o.CreatedDate > date);
Where
方法两次。 - MarcinJuraszekidSelector
是一个属性表达式,那么你可以使用它来代替Invoke
。如果你不能这样做,你就必须尝试递归地解构它,并构建一个不使用Invoke
的新表达式。请参见更新。 - Lee.AndAlso
,然后我才能得到正确的行为:// 使用AndAlso => 'AND'操作符组合表达式。不要使用And => '&' queryExpression = Expression.AndAlso(smallerExp, largerExp);
谢谢! - Jones