Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper mapping to a property of a nullable property

Tags:

c#

automapper

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.

like image 352
David Gardiner Avatar asked Nov 04 '10 00:11

David Gardiner


People also ask

Does AutoMapper handle null?

The Null substitution allows us to supply an alternate value for a destination member if the source value is null. That means instead of mapping the null value from the source object, it will map from the value we supply.

How does AutoMapper work internally?

How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.

How do I ignore source property AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

Where is AutoMapper configuration?

Where do I configure AutoMapper? ¶ Configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.


1 Answers

You could write the mapping code like follows:

Mapper.CreateMap<Contact, ContactModel>()
            .ForMember( x => x.UserName,  opt => opt.MapFrom( y => (y.User != null) ? y.User.UserName : "" ) );

This will check if the User is null or not and then assign either an emtpy string or the UserName.

like image 112
davehauser Avatar answered Oct 19 '22 22:10

davehauser