Question

I'm using an automapper to flatten the object coming from WS. Simplified model would be as follows:

public abstract class AOrder {
    public Product Product {get;set;}
    public decimal Amount {get;set;}
    //number of other properties
}

public abstract class Product {
    //product properties
}
public class RatedProduct : Product {
   public int Rate { get;set;}
}

public class MarketOrder : AOrder {
    //some specific market order properties
}

Using automapper I'm trying to flatten this into:

public class OrderEntity {
   public decimal Amount {get;set;}
   public int ProductRate {get;set;}
}

with next mapping:

CreateMap<RatedProduct, OrderEntity>();
CreateMap<MarketOrder, OrderEntity>();

The above mapping will not map the ProductRate. Atm I've just used the AfterMap:

CreateMap<MarketOrder, OrderEntity>()
    .AfterMap((s,d) => {
         var prod = s.Product as RatedProduct;
         if (prod != null) 
         {
             //map fields
         }
     });

which works pretty well, but thought if I could reuse the automapper flattening possibilities (i.e. matching by name) I wouldn't need to apply the after map in quite many places.

Note: I can't change the WS and this is just a tiny part from object hierarchy.

Advice appreciated.

Était-ce utile?

La solution

Mapping Rate to ProductRate is fairly straight forward with "ForMember"

The one where you have to do a cast to the specific type to see if it is that type is a little trickier but I think the same approach you took is what you might have to do however I don't think you need to do "aftermap". I thought all your destination mappings had to be found OR you need to mark them as ignore of the mapping will fail.

Another thing you could do is just change the OrderEntity.ProductRate to be OrderEntity.Rate. Then it would find it and map it for you except where it was hidden because Product doesn't have a rate (but RatedProducts do).

public class OrderEntity {
   public decimal Amount {get;set;}
   public int Rate {get;set;}  //changed name from ProductRate to just Rate.
}

 Mapper.CreateMap<Product, OrderEntity>()
    .Include<RatedProduct, OrderEntry>();

 Mapper.CreateMap<RatedProduct, OrderEntry>();

SEE: Polymorphic element types in collections

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top