使用 automapper 将过滤器应用于集合 [英] Using automapper to apply a filter to a collection

查看:21
本文介绍了使用 automapper 将过滤器应用于集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含集合的域模型,我想使用 AutoMapper 将父级和子级映射到视图模型,但我不希望被软"删除的子级被接受.例如:

I have a domain model that contains a collection and I want to use AutoMapper to map the parent and children to the view model but I don't want children that have been "soft" deleted to be taken across. For instance:

public class Customer {
   public EntitySet<Order> {get;set;}
}
public class Order {
   public DateTime? DeletedDate {get;set;}
}

我的 AutoMapper 定义是

my AutoMapper definition would be

Mapper.CreateMap<Customer, CustomerViewModel>();
Mapper.CreateMap<Order, OrderViewModel>();

并且我不希望 Orders 位于具有 DeletedDate 值的视图模型中.

and I don't want Orders to be in the view model that have a value for DeletedDate.

这在 AutoMapper 中可行吗?非常感谢,

Is that possible in AutoMapper? Many thanks in advance,

史蒂夫.

推荐答案

我遇到了类似的问题,最后类似于下面的方法对我有用:

I came across similar issue and finally the approach similar to the one below worked for me:

Mapper.CreateMap<Customer, CustomerViewModel>()
    .ForMember(dest => dest.Orders, 
        opt => opt.MapFrom(src => src.Orders.Where(o => !o.DeletedDate.HasValue)));

这假设您的 Customer 实体和 CustomerViewModel d 具有名为Orders"的集合.

This assumes your Customer entity and CustomerViewModel dto have collections named "Orders".

这篇关于使用 automapper 将过滤器应用于集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆