AutoMapper: Ignore specific dictionary item(s) during mapping

Viewed 803

Context:

There 2 main classes that look something like this:

public class Source
{
   public Dictionary<AttributeType, object> Attributes { get; set; }
}

public class Target
{
   public string Title { get; set; }
   public string Description { get; set; }
   public List<Attribute> Attributes { get; set; }
}

And the sub / collection / Enum types:

public class Attribute
{
   public string Name { get; set; }
   public string Value { get; set; }
}

public enum AttributeType
{
    Title,
    Description,
    SomethingElse,
    Foobar
}

Currently my Map looks like this:

 CreateMap<Source, Target>()
  .ForMember(dest => dest.Description, opt => opt.MapAttribute(AttributeType.Description))
  .ForMember(dest => dest.Title, opt => opt.MapAttribute(AttributeType.Title));

Where MapAttribute gets the item from the Dictionary and using the AttributeType I've provided, adds it to the target collection as a (name & value) object (using a try get and returning an empty if the key does not exist)...

After all of this my Target set end's up looking like this:

{ 
  title: "Foo", 
  attributes: [
     { name: "SomethingElse", value: "Bar" }, 
     { name: "Title", value: "Foo"}
  ] 
}


Question:

How do I go about mapping the rest of the items to the target class, but I need to be able to exclude specific keys (like, title or description). E.G. Source.Attribute items that have a defined place in target gets excluded from the Target.Attributes collection, and "left-over" properties still go to Target.Attributes.

For even more clarity (if my source looks like this):

{ attributes: { title: "Foo", somethingelse: "Bar" } }

it would map to a target like this:

{ title: "Foo", attributes: [{ name: "SomethingElse", value: "Bar" }] }

I've attempted this, but it does not compile, stating the following:

Custom configuration for members is only supported for top-level individual members on a type.

CreateMap<KeyValuePair<AttributeType, object>, Attribute>()
   .ForSourceMember(x => x.Key == AttributeType.CompanyName, y => y.Ignore())
1 Answers
Related