Automapper append source list items to destination list

1.9k views Asked by At

I am trying to map List<string> property but I want in destination object to always have default value. On the source object list can be empty or it can contain other values.

If the list is empty then the Destination property will contain only the default value that is defined in the constructor.

If the list contains some data, then Source values should be appended in the list.

Here is my code:

    List<string> _accessRights;
    public User()
    {
        _accessRights = new List<string>() { "user" };
    }
    public List<string> AccessRights
    {
        get { return _accessRights; }
        set { _accessRights = value; }
    }

Here is the example how I would use it.

UserModel user = new UserModel() { access_rights = new List<string>() { "power_user", "admin" } };
        User dbUser = Mapper.Map<User>(user);

As a result I would like to have user, power_user, admin saved in the database. If the access_rights was null then I would expect to have only user.

Is that possible?

1

There are 1 answers

4
Thiago Sá On BEST ANSWER

You can create the map like this:

Mapper.CreateMap<UserModel, User>()
      .ForMember(user => user._accessRights, opt => opt.MapFrom(src => src.accessRights != null ?
        src.accessRights.Union(new User()._accessRights) : new User()._accessRights));