首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在ardalis.Specification库中定义选择器?

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

Stack Overflow用户
提问于 2022-04-21 16:01:06
回答 1查看 886关注 0票数 4

我正在尝试利用Ardalis.Specification库在我的asp.net 6项目中应用规范模式。

安装库后,我创建了以下规范

代码语言:javascript
代码运行次数:0
运行
复制
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()定义,但给出了相同的错误

代码语言:javascript
代码运行次数:0
运行
复制
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 });
    }

}
EN

回答 1

Stack Overflow用户

发布于 2022-09-28 03:43:23

代码语言:javascript
代码运行次数:0
运行
复制
public class ProductByIdsSpec : Specification<Product, ProductMenuItem>
{
    public ClientRecordByIdsSpec(IEnumerable<int> ids)
    {
        ...
    }

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

可以在指定类中覆盖Selector属性,并在那里实现投影

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71957514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档