我正在尝试利用Ardalis.Specification库在我的asp.net 6项目中应用规范模式。
安装库后,我创建了以下规范
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
public ClientRecordByIdsSpec(IEnumerable<int> ids)
{
if (ids == null || !ids.Any())
{
return;
}
Query.Where(x => ids.Contains(x.Id));
// some how I need to map Product to ProductMenuItem so only the needed columns are pulled from the database.
}
}
与其从数据库中提取Product
中的每个值,我只想通过将数据投影到ProductMenuItem
来提取所需的数据。上面的规范返回以下错误
Ardalis.Specification.SelectorNotFoundException:规范必须定义SelectorNotFoundException选择器
如何定义实体(即Product
)和结果对象(即ProductMenuItem
)之间的映射?
我试图添加Select()
定义,但给出了相同的错误
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
public ClientRecordByIdsSpec(IEnumerable<int> ids)
{
if (ids == null || !ids.Any())
{
return;
}
Query.Where(x => ids.Contains(x.Id));
Query.Select(x => new ProductMenuItem() { Name = x.Name, x.Id = x.Id });
}
}
发布于 2022-09-28 03:43:23
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
public ClientRecordByIdsSpec(IEnumerable<int> ids)
{
...
}
public override Expression<Func<Product, ProductMenuItem>> Selector { get; }
= (product) => new ProductMenuItem();
}
可以在指定类中覆盖Selector属性,并在那里实现投影
https://stackoverflow.com/questions/71957514
复制相似问题