KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
How can you map a property to a sub-property that may be null? eg the following code will fail with a NullReferenceException because the Contact's User property is null. using AutoMapper; namespace AutoMapperTests { class Program { static void Main( string[] args ) { Mapper.CreateMap<Contact, ContactModel>() .ForMember( x => x.UserName, opt => opt.MapFrom( y => y.User.UserName ) ); Mapper.AssertConfigurationIsValid(); var c = new Contact(); var co = new ContactModel(); Mapper.Map( c, co ); } } public class User { public string UserName { get; set; } } public class Contact { public User User { get; set; } } public class ContactModel { public string UserName { get; set; } } } I'd like ContactModel's UserName to default to an empty string instead. I have tried the NullSubstitute method, but I assume that's trying to operate with User.Username, rather than just on the User property.
Tags (comma-separated)
Save Edits
Cancel