Blaise
Blaise

Reputation: 22212

How to keep original value of a source property in Automapper mapping?

The input view model:

public class FacilityInputModel 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

The domain model:

public class FacilityInputModel 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string OriginalName { get; set; }
}

I am to allow users to change the name of a facility but still keep its original name.

Say facility is (I am writing json just for convenience)

{id:1, name='Facility1', originalName='Facility1'}

when created.

I am to change the name by posting a FacilityInputModel.

{id:1, name='Facility2'}

In C# code to update the entity:

var entity = _repository.Find(id);
_repository.Detach(entity);
entity = Mapper.Map<Facility>(model);

_repository.Update(entity);
_repository.Save();

The entity I get before Mapper.Map

{id:1, name='Facility1', originalName='Facility1'}

But after the mapping, the entity is

{id:1, name='Facility2', originalName=null}

instead of

{id:1, name='Facility2', originalName='Facility1'}

In my mapping, I tried to Ignore the OriginalName

CreateMap<Facility, FacilityInputModel>()
    .ReverseMap()
    .ForMember(x => x.OriginalName, opt => opt.Ignore());

But it never worked. Also tried

    .ForMember(x => x.NameInWebAdmin, opt => opt.DoNotUseDestinationValue());

Still won't work.

So the question is how to avoid existing values from being wiped away in the mapping. And get an after-mapping entity:

{id:1, name='Facility2', originalName='Facility1'}

Upvotes: 6

Views: 4721

Answers (1)

user848765
user848765

Reputation:

You're getting a completely new object when you call entity = Mapper.Map<Facility>(model);. Try using Mapper.Map<Source, Destination>(source, destination) to map to an existing one.

Upvotes: 13

Related Questions