如何在 ardalis.Specification 库中定义选择器?

问题描述 投票:0回答:2

我正在尝试利用 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 });
    }

}
c# asp.net-core specifications specification-pattern ardalis-specification
2个回答
0
投票
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
    public ClientRecordByIdsSpec(IEnumerable<int> ids)
    {
        ...
    }

    public override Expression<Func<Product, ProductMenuItem>> Selector { get; }
        = (product) => new ProductMenuItem();
}

您可以覆盖Specification类中的Selector属性并在那里实现您的投影

https://github.com/ardalis/Specification/blob/main/Specification/src/Ardalis.Specification/Specification.cs#L29


0
投票

从今天开始,这对我有用。在该库的当前实现中,

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

}
© www.soinside.com 2019 - 2024. All rights reserved.