【问题标题】:Automapper "map a few and ignore the rest"Automapper“映射一些并忽略其余的”
【发布时间】:2022-09-24 12:11:11
【问题描述】:

我知道关于这个但是有很多问题(和答案)没有任何在使用 .net6 和 automapper 11.01.1 时,这些对我有用 他们似乎在最新的自动映射器中删除了许多 IgnoreIgnoreAllUnmappedForAllOtherMembers。 如果我对ForAllMembers 使用ignore(在ForMember 之前或之后),它将忽略所有字段,即使是我用地图指定的字段。

问题:我有两个具有相同名称字段的类,但我只想映射一些并忽略其余部分。 (请不要说“为什么需要自动映射器”,这不是这里的问题)。

在这种情况下我需要使用 automapper 但不确定他们是否支持这个?我可能错过了一个nuget吗?我只使用“AutoMapper 11.01.1”

public class User1
{
    public string Name { get; set; } = \"Foo\";
    public int Age { get; set; } = 7;
    public string Phone { get; set;} = \"123456789\";
}
public class User2
{ 
    public string FirstLastName { get; set; }
    public int Age { get; set; }
    public string Phone { get; set; }
}

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<User1, User2>()
            .ForMember(dest => dest.FirstLastName, opt => opt.MapFrom(src => src.Name))
            //.ForMember(dest => dest.Age, src => src.Ignore());  // works BUT I do not want to ignore every field manually
            //.ForAllMembers(dest => dest.Ignore())               // doesn\'t work, clears all fields
            //.ValidateMemberList(MemberList.None)                // doesn\'t work
            ;
    }
}

void Main()
{
    var user1 = new User1();
    
    var config = new MapperConfiguration(mc => mc.AddProfile(new AutoMapperProfile()));
    Mapper mapper = new Mapper(config);
    
    var user2 = mapper.Map<User2>(user1);
    user2.Dump();
}

标签: c# mapping automapper


【解决方案1】:

我们遇到了同样的问题。我创建了这个扩展方法,它应该提供您正在寻找的功能。

public static IMappingExpression<TSource, TDestination> IgnoreAllMembers<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expr)
{
    var destinationType = typeof(TDestination);

    foreach (var property in destinationType.GetProperties())
        expr.ForMember(property.Name, opt => opt.Ignore());

    return expr;
}

它的用途:

CreateMap<ModelOne, ModelTwo>()
    .IgnoreAllMembers()
    .ForMember(x => x.DescriptionOne, opt => opt.MapFrom(y => y.DescriptionOne));

它通过循环遍历目标类型的所有属性并忽略它们来工作。这意味着它需要被调用您提供您的成员映射。之后调用它会覆盖您的映射。

希望这可以帮助。

【讨论】:

  • 太好了,谢谢你的回复。我想再也没有办法用 automapper 做到这一点了,这太奇怪了。
【解决方案2】:

我改变了普伦以前的答案。非常感谢他。这是一种忽略目标属性中不存在的方法。

public static IMappingExpression<TSource, TDestination> IgnoreNonExistingMembers<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expr)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);

    foreach (var property in destinationType.GetProperties())
    {
        if (sourceType.GetProperty(property.Name) != null)
            continue;
        expr.ForMember(property.Name, opt => opt.Ignore());
    }

    return expr;
}

【讨论】:

    猜你喜欢
    • 2010-10-31
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2023-01-26
    • 2017-12-31
    相关资源
    最近更新 更多