You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AutoMapper映射集合时设置元素的IsDefault属性

解决方案

以下是几种实现需求的AutoMapper用法,可根据场景选择:

方法一:直接结合Select手动设置属性

这种方式简单直接,无需提前配置复杂映射规则,适合快速实现:

var container = Container.Build();

// 遍历源集合,逐个映射并设置IsDefault
var newCollection = container.SourceCollection
    .Select(source => 
    {
        var destination = mapper.Map<Destination>(source);
        destination.IsDefault = source.ID == container.DefaultID;
        return destination;
    });

方法二:通过AutoMapper上下文传递参数配置映射

如果需要复用映射规则,或者希望映射逻辑更内聚,可以通过上下文参数传递DefaultID,提前配置映射:

第一步:配置映射规则

var mapperConfig = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Source, Destination>()
        // 利用上下文传入的DefaultID判断是否设为默认
        .ForMember(dest => dest.IsDefault, opt =>
            opt.MapFrom((source, _, __, context) => 
                source.ID == context.Items["DefaultID"] as string));
});

var mapper = mapperConfig.CreateMapper();

第二步:使用映射并传入参数

var container = Container.Build();

// 映射时通过Options传入DefaultID
var newCollection = mapper.Map<IEnumerable<Destination>>(
    container.SourceCollection,
    opt => opt.Items["DefaultID"] = container.DefaultID
);

说明

因为Destination继承自Source,AutoMapper会自动处理基类中ID和Color属性的映射,无需额外配置。两种方法都能实现需求:仅ID与Container.DefaultID匹配的元素,其IsDefault属性设为true,其余为false。

内容的提问来源于stack exchange,提问作者Brea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:05:29