AutoMapper 使用 Conventions 映射出错

2019-04-24 00:19发布

问题:

使用 AutoMapper 7.0..1 转换出错!

public class User
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string UserName { get; set; }
    }

public class UserOutput
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Account { get; set; }

    }
Mapper.Initialize(
                cfg =>
                {
                    cfg.AddMemberConfiguration()
                        .AddMember<NameSplitMember>()
                        .AddName<PrePostfixName>(_ => _.AddStrings(p => p.Postfixes, "Output"));
                    cfg.AddConditionalObjectMapper().Where((s, d) => s.Name == d.Name + "Output");

                    cfg.AddMemberConfiguration()
                        .AddMember<NameSplitMember>()
                        .AddName<PrePostfixName>(_ => _.AddStrings(p => p.DestinationPostfixes, "Input"));
                    cfg.AddConditionalObjectMapper().Where((s, d) => d.Name == s.Name + "Input");
                });

var user = new User
{
      Id = 1,
      Name = "管理员",
      UserName = "admin"
};

 Mapper.Map<User, UserOutput>(user);

UserOutput 中多出一个 Account 属性,在 User 中不存在,导致无法转换成功,如果直接使用 cfg.CreateMap<User, UserOutput>() 创建配置是可以转换成功,但是这样需要多出许多配置的语句。

求解?

回答1:

http://docs.automapper.org/en/stable/Inline-Mapping.html



标签: AutoMapper