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

Jay*_*Jay 5 c# specifications specification-pattern asp.net-core ardalis-specification

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

}
Run Code Online (Sandbox Code Playgroud)

我不想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 });
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 0

public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
    public ClientRecordByIdsSpec(IEnumerable<int> ids)
    {
        ...
    }

    public override Expression<Func<Product, ProductMenuItem>> Selector { get; }
        = (product) => new ProductMenuItem();
}
Run Code Online (Sandbox Code Playgroud)

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

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