gpt4 book ai didi

c# - 通过匹配谓词方法获取项目

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:32 25 4
gpt4 key购买 nike

我正在尝试使用谓词实现通用方法。我写了一些代码:

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);

最后,我遇到了无效操作异常:类型“System.Linq.Queryable”上的泛型方法“Where”与提供的类型参数和参数不兼容。

我的代码有什么问题?感谢您的提前!

最佳答案

context.Products.Where(predicate) 中的谓词显然只能是 Expression<Func<Product, bool>> , 不是 Expression<Func<T, bool>> ,因为不能保证 TProduct .

您正在尝试过滤目标类型的谓词,而过滤必须发生在源类型上:

public ICollection<T> GetProductsByMatching<T>(Expression<Func<Product, bool>> predicate)
{
return context.Products.Where(predicate)
.Include("ShopPlace, Images")
.ProjectTo<T>()
.ToList();

}

关于c# - 通过匹配谓词方法获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com