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);
    }
}

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

相关内容

热门资讯

透视脚本!wpk透视工作室,拱... 透视脚本!wpk透视工作室,拱趴大菠萝挂,安装教程(有挂攻略);拱趴大菠萝挂软件透明挂作为一款拱趴大...
每日必看!来玩app辅助工具,... 每日必看!来玩app辅助工具,wepoke智能ai,插件教程(都是真的有挂)是一款可以让一直输的玩家...
如何分辨真伪!德扑数据分析软件... 如何分辨真伪!德扑数据分析软件,wepoke辅助有挂,扑克教程(一向是有挂)是一款可以让一直输的玩家...
透视软件!hhpoker透视脚... 透视软件!hhpoker透视脚本视频,边锋斗地主辅助微信,揭秘教程(有挂教程);人气非常高,ai更新...
必看攻略!wepoke透明挂辅... 一、wpk外挂简介了解软件请加微:136704302wpk外挂是一款在线扑克游戏平台,玩家可以在平台...
透视私人局!hhpoker免费... 1、透视私人局!hhpoker免费透视脚本,好友赣南插件,AI教程(有挂方法);详细教程。2、好友赣...
教程攻略!aa poker下载... 教程攻略!aa poker下载地址,微扑克系统发牌规律,第三方教程(一贯是真的有挂)微扑克系统发牌规...
透视模拟器!wepoker透视... 透视模拟器!wepoker透视,蘑菇云辅助使用视频,AI教程(有挂教程)是由北京得蘑菇云辅助使用视频...
关于!wepoke有吗,智星德... 自定义智星德州菠萝有挂吗系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不...
透视app!wpk透视脚本视频... 透视app!wpk透视脚本视频,掌中乐游戏中心破解版,第三方教程(有挂技巧)是一款可以让一直输的玩家...