c# - 列表场景的 AutoMapper 似乎只重复映射列表中的第一个对象

标签 c# asp.net-mvc automapper

我正在开发一个 MVC 3 应用程序并使用 AutoMapper 在我的 ViewModel 和我的实体之间移动数据。我有一个场景,我需要在两个列表之间移动数据。由于某些奇怪的原因,AutoMapper 似乎只从源对象复制第一个对象,然后似乎将同一个对象复制 n 次到目标列表。例如,假设您有 2 个列表,source 包含 6 个实体项,destination 包含 0 个项,因为它刚刚被实例化。源 [0] 位置的项目被复制到目的地,然后源 [0] 被重复复制源列表中相同数量的项目,在本例中为 6。我不明白可能是什么原因。

这是 AutoMapper 配置文件:

public static class AutoMapperConfigurator
{
    public static void Configure()
    {
        Mapper.CreateMap<User, UserModel>();
        Mapper.CreateMap<Posting, PostingModel>();
    }
}

这里是Global.asax文件设置

protected void Application_Start()
{
    AutoMapperConfigurator.Configure();
}

这里是我调用Map方法的位置

userSearchModel.UserList = Mapper.Map<IList<User>, IList<UserModel>>(userEntities);

最佳答案

所以,一个合适的解决方案,但不是我们在使用 AutoMapper 时想要的。

当您错误地覆盖被映射的实体/模型的 Equals 方法时,这个问题很常见。

例如,如果您尝试映射上面的对象列表,您只会从 SourceEntity 中获取第一个对象。

    public class SourceEntity 
    {
         public string MyField {get; set;}         

         public override bool Equals(object obj)
         {
              return true;
         }
    }

    public class TargetEntity 
    {
          public string MyField {get; set;}  
    }

检查 Equals 方法是否返回 true。

关于c# - 列表场景的 AutoMapper 似乎只重复映射列表中的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17268362/

相关文章:

c# - 使用 Linq 在 C# 中进行列表操作

javascript - CefSharp C# 更改 navigator.appName 为 javascript

identityserver4 的 Automapper 问题 - MissingMethodException : Method not found: '!!0 AutoMapper.IMapper.Map(System.Object)'

c# - 如何使用 Automapper 映射复杂对象?

c# - 一种类型的属性映射到另一种类型的实例

c# - AvalonDock:多工具窗口布局

c# - 如何防止它在listview中被添加2次

javascript - jQuery Mask-Money 不工作 MVC5

Asp.net Web API DateTimeOffset 设置与 http header 的偏移量

c# - OwinStartupAttribute 不应该在 global.asax 和 Application_Start 之前运行吗?