AutoMapper不会更新集合中的项目。
创始人
2024-09-23 11:31:12
0

在使用AutoMapper时,确实无法直接更新集合中的项目。但是,可以通过以下几种方式来解决这个问题:

  1. 使用循环遍历集合,并逐个映射和更新项目。
foreach (var sourceItem in sourceList)
{
    var destinationItem = destinationList.FirstOrDefault(d => d.Id == sourceItem.Id);
    if (destinationItem != null)
    {
        // 使用AutoMapper映射属性
        Mapper.Map(sourceItem, destinationItem);
        // 更新其他属性
        destinationItem.OtherProperty = sourceItem.OtherProperty;
    }
    else
    {
        // 如果目标集合中不存在对应的项目,则将源项目映射为目标项目并添加到目标集合中
        destinationItem = Mapper.Map(sourceItem);
        destinationList.Add(destinationItem);
    }
}
  1. 使用自定义映射配置来处理集合映射。
Mapper.Initialize(cfg =>
{
    cfg.CreateMap()
        .ForMember(dest => dest.Id, opt => opt.Ignore()) // 忽略Id属性,以便手动处理
        // 其他映射配置
        // ...
        ;
});

foreach (var sourceItem in sourceList)
{
    var destinationItem = destinationList.FirstOrDefault(d => d.Id == sourceItem.Id);
    if (destinationItem != null)
    {
        // 使用AutoMapper映射属性
        Mapper.Map(sourceItem, destinationItem);
        // 更新其他属性
        destinationItem.OtherProperty = sourceItem.OtherProperty;
    }
    else
    {
        // 如果目标集合中不存在对应的项目,则将源项目映射为目标项目并添加到目标集合中
        destinationItem = Mapper.Map(sourceItem);
        destinationList.Add(destinationItem);
    }
}
  1. 使用手动映射来更新集合中的项目。
foreach (var sourceItem in sourceList)
{
    var destinationItem = destinationList.FirstOrDefault(d => d.Id == sourceItem.Id);
    if (destinationItem != null)
    {
        // 手动映射属性
        destinationItem.Property1 = sourceItem.Property1;
        destinationItem.Property2 = sourceItem.Property2;
        // 更新其他属性
        destinationItem.OtherProperty = sourceItem.OtherProperty;
    }
    else
    {
        // 如果目标集合中不存在对应的项目,则将源项目映射为目标项目并添加到目标集合中
        destinationItem = new DestinationItem
        {
            Id = sourceItem.Id,
            Property1 = sourceItem.Property1,
            Property2 = sourceItem.Property2,
            // 其他属性
            OtherProperty = sourceItem.OtherProperty
        };
        destinationList.Add(destinationItem);
    }
}

以上是几种解决方法的示例代码,具体的实现方式可以根据实际需求和项目结构进行调整。

相关内容

热门资讯

教程攻略"福建十三水... 您好:这款福建十三水辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款福建十三水辅助游戏中打牌都会发...
新手必备"天蝎辅助&... 新手必备"天蝎辅助"开挂(透视)wepoker轻量版辅助(有挂技术)wepoker轻量版辅助ai黑科...
玩家必看教程"斗棋联... 玩家必看教程"斗棋联盟俱乐部辅助挂"开挂(透视)hhpoker怎么防作弊(有挂攻略)1、下载安装好斗...
透视计算"开心酷跑破... 开心酷跑破解版 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、...
总算了解"白银胡乐亲... 白银胡乐亲友房开挂教程视频分享装挂详细步骤在当今的网络游戏中,白银胡乐亲友房作为一种经典的娱乐方式,...
记者爆料"玄龙辅助工... 您好:wepoker透视底牌脚本这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
实操分享"葫芦娃七子... 实操分享"葫芦娃七子降妖破解版内购"开挂(透视)德扑圈透视(讲解有挂)1、下载安装好葫芦娃七子降妖破...
一分钟教会你"宝宝浙... 一分钟教会你"宝宝浙江游戏有没有辅助器"开挂(透视)wpk俱乐部辅助器(有挂解惑);无需打开直接搜索...
交流学习经验"多乐够... 交流学习经验"多乐够级辅助软件"开挂(透视)we poker游戏下(有挂技巧)《详细加薇136704...
大神推荐"打两圈兴化... 大神推荐"打两圈兴化辅助"开挂(透视)we-poker靠谱吗(有挂头条)1、下载安装好打两圈兴化辅助...