【发布时间】:2016-03-31 20:04:21
【问题描述】:
我正在尝试使用谓词实现一个通用方法。 我写了一些代码:
public ICollection<T> GetProductsByMatching<T>(Expression<Func<T, bool>> predicate)
{
return context.Products.Where(predicate).Include("ShopPlace, Images").ProjectTo<T>().ToList();
}
以及这个方法的用法:
var a = service.GetProductsByMatching<ProductInfo>(x => x.Name.StartsWith("value")
|| x.Price < 150);
最后我有Invalid Operation Exception:类型“System.Linq.Queryable”上没有通用方法“Where”与提供的类型参数和参数兼容。
我的代码有什么问题?感谢您的提前!
【问题讨论】:
-
因为
T!=Product。这段代码应该做什么?你的意思是打电话给context.Set<T>吗? -
@CodeCaster 通过谓词从数据库中获取产品并将其映射到 ProductInfo(ViewModel 类)
-
是的,that 部分在代码中很明显,但我想首先找出您输入
Expression<Func<T, bool>>的原因。在我的回答中,我现在根据方法名称做了一些假设。
标签: c# entity-framework linq