ProfK
ProfK

Reputation: 51063

How can I make Automapper set a reference to the source object in the destination object?

In the application I am busy writing, all my mapping destination objects derive from a base class like this:

public class CatalogObject<TObject>
{
    TObject InnerObject { get; set; }
}

public class CatalogTable : CatalogObject<table>
{
    public string Name { get; set; }
    public int ObjectId { get; set; }
}

Now, after mapping a table object to a CatalogTable object, I want the InnerObject property of that destination to be a reference to the source table object.

Upvotes: 2

Views: 1121

Answers (1)

Mightymuke
Mightymuke

Reputation: 5144

You could do it with a Custom Resolver:

Mapper.CreateMap<Table, CatalogTable>()
    .ForMember(dest => dest.InnerObject,
               opt => opt.ResolveUsing<InnerObjectResolver>());

Where the resolver would look something like:

public class InnerObjectResolver : ValueResolver<Table, Table>
{
    protected override Table ResolveCore(Table source)
    {
        return source;
    }

}

Full details can be found in the custom resolver documentation.

You might also be able to do it directly, but I haven't tried that. Something like this maybe:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.InnerObject, opt => opt.MapFrom(src => src));

Upvotes: 1

Related Questions