Roni
Roni

Reputation: 403

AutoMapper C# - Set default value for all unmapped string in destination

I'm new to AutoMapper, and trying convert object to bigger (means more fields) object. I'm looking for a way to set default value for all destination's string fields. Currently couldn't find a way to define general condition for all string fields.

Assume:

  class A
{
    public string a { get; set; }

}

class B
{
    public DateTime DateTime { get; set; }
    public string a { get; set; }
    public string b { get; set; }
    public string c { get; set; }
}

Then when using mapper:

var config = new MapperConfiguration(cfg => cfg.CreateMap<A, B>());       
            var mapper = config.CreateMapper();
            B map = mapper.Map<B>(new A {a = "f"});

The unmapped strings' value is null. I'm looking for a way to set the unmapped strings to string.Empty. Using the config.ForAllMembers(...). Note: I know I can use specific ForMember for each field like:

 var config = new MapperConfiguration(cfg => cfg.CreateMap<A, B>()
           .ForMember(des => des.b, x=> x.MapFrom(src => string.Empty)));       

But it isn't so good. Why?

  1. Some times I have fields that their value isn't guaranteed, it may be null or a valid value so I need to pay attention for such case.
  2. In real case I have many fields, so it's not a comfortable solution to define such rule for every field.

There is an easy solution for such need?

Upvotes: 2

Views: 16866

Answers (4)

FabioStein
FabioStein

Reputation: 920

I used this approach which gives more control for your default values to be set in the destination class

public class User
{
    public string Name { get; set; }
}

public class UserDto
{
    public string Name { get; set; } = "Guest";
}
public class UserDtoProfile : Profile
{
    public UserDtoProfile()
    {
        CreateMap<User, UserDto>()
            .ForAllMembers((c) =>
            {
                c.UseDestinationValue();
            });
    }
}

Upvotes: 0

Alison Niu
Alison Niu

Reputation: 74

.ForMember(dest => dest.field, act => act.MapFrom(src => default))

put default as defaultValue directly.

Upvotes: 0

Panayiotis Savva
Panayiotis Savva

Reputation: 131

I have managed to resolve in the following manner:

.ForMember(dest => dest.field, act => act.MapFrom(src => String.IsNullOrEmpty(src.field) ? "N/A" : src.field))

Upvotes: 2

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

One idea is to use ForAllOtherMembers.

    c.CreateMap<A, B>().ForAllOtherMembers(o=>
    {
        if(((PropertyInfo)o.DestinationMember).PropertyType == typeof(string))
        {
            o.MapFrom(s=>"default");
        }
    });

Upvotes: 0

Related Questions