Reputation: 14550
Using automapper to fetch first image that is the 'IsMain' and will set PhotoUrl to null if no image exists. But now I want to check if the image is null and add another condition to set the url to something else, such as
if (src.Photos.FirstOrDefault(p => p.IsMain) == null) {
if (user.gender == 'male') {
// set PhotoUrl to something here
}
}
here is my automapper create map call
CreateMap<User, UserForListDto>()
.ForMember(dest => dest.PhotoUrl, opt => {
opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url);
})
});
I tried adding an extension like this, but it doesn't even get called if the value is null.
opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url.GetDefaultMemberImage(src.Gender));
public static string GetDefaultMemberImage(this string photoUrl, string gender) {
if (photoUrl == null) {
if (gender == "male") {
return "url1";
} else {
return "url2";
}
} else {
return photoUrl;
}
}
I was thinking I could change "src.Photos.FirstOrDefault()" to something else, but not sure what?
Upvotes: 1
Views: 1118
Reputation: 29996
For opt.MapFrom
, you could use expression to check whether the src.Photos.FirstOrDefault(p => p.IsMain)
is null.
Try something like
CreateMap<UserPhoto, UserPhotoDto>()
.ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(src =>
src.Photos.FirstOrDefault(p => p.IsMain) == null ? (src.Gender == "male" ? "url1" : "url2") : src.Photos.FirstOrDefault(p => p.IsMain).Url));
Upvotes: 1