Reputation: 403
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?
There is an easy solution for such need?
Upvotes: 2
Views: 16866
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
Reputation: 74
.ForMember(dest => dest.field, act => act.MapFrom(src => default))
put default as defaultValue directly.
Upvotes: 0
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
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