AutoMapper Ignore not working on entity update

automapper-6 c# entity-framework-6

Question

I Know this question was answered in another thread. And I tried what was suggested but it still not working.

Here is my entity and model mapping...

cfg.CreateMap<DocumentAmountModel, InputDocumentData>()                    
       .ForMember(d => d.Amounts, o => o.MapFrom(s => s.Amounts));

Mapping for the child Amounts

cfg.CreateMap<ItemAmountModel, Amount>()
            //Ignore the Keys for update
            .ForMember(a => a.Id, o => o.Ignore())
            .ForMember(a => a.ItemId, o => o.Ignore())

And I am trying to ignore the PKs and FKs in the entity from being updated with what is in model.

On the service layer- the entity is loaded with data from Db and then calling the mapper to update all the property other than FK & PK as follows.

var doc = _docDataR.GetAll()
                .Where(d => d.Id==1)
                .SingleOrDefault<InputDocumentData>();

Mapper.Map<DocumentAmountModel, InputDocumentData>(model, doc);

To my surprise, Amount.Id and Amount.ItemId are always updated with 0 on the child Amounts. Am missing anything obvious?

PS: The entity instance "doc" is not proxy, so it is not about being proxy that could have caused improper mapping.

1
0
5/3/2017 3:41:12 PM

Popular Answer

When it comes to collection as child, AutoMapper recreates the entity (Destination) collection. In order to instruct AutoMapper to use existing collection, the configuration has to be done as follows...

Step 1: Call the AddCollectionMappers() - this what I missed.

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers(); //This is must        
});

Step 2: Use EqualityComparison method to instruct AM on how to match the item in the source collection to the destination.

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers(); 

    cfg.CreateMap<DocumentAmountModel, InputDocumentData>()                    
       .ForMember(d => d.Amounts, o => o.MapFrom(s => s.Amounts));

   cfg.CreateMap<AmountModel, Amount>()
      .EqualityComparison((model, e) => model.Code == e.Code);
});

Step 3: Ignore any properties such as PKs, FKs that should not be updated from Model

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers(); 

    cfg.CreateMap<DocumentAmountModel, InputDocumentData>()                    
       .ForMember(d => d.Amounts, o => o.MapFrom(s => s.Amounts));

   cfg.CreateMap<AmountModel, Amount>()
      .EqualityComparison((model, e) => model.Code == e.Code)
      .ForMember(e => e.Id, o => o.Ignore());

});

For more detail...

https://github.com/AutoMapper/AutoMapper.Collection

0
10/31/2017 6:16:17 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow