我正在尝试利用 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
来提取所需的数据。上述规范返回以下错误
SelectorNotFoundException Ardalis.Specification.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 });
}
}
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
public ClientRecordByIdsSpec(IEnumerable<int> ids)
{
...
}
public override Expression<Func<Product, ProductMenuItem>> Selector { get; }
= (product) => new ProductMenuItem();
}
您可以覆盖Specification类中的Selector属性并在那里实现您的投影
从今天开始,这对我有用。在该库的当前实现中,
Selector
属性是通过 ISpecificationBuilder
设置的,这并不明显。我宁愿检查单元测试和代码而不是文档。
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
public ClientRecordByIdsSpec(IEnumerable<int> ids)
{
if (ids == null || !ids.Any())
{
return;
}
Query
.Select(x => new ProductMenuItem() { Name = x.Name, x.Id = x.Id });
.Where(x => ids.Contains(x.Id));
}
}