简体   繁体   中英

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'}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM