简体   繁体   中英

c# auto mapper how to add auto-increment property to destination projection?

We have source object "StockBase" and destination object as "StockDTO". While mapping "StockBase" to "StockDTO", we want to add a property that would give the index of collection ie auto increment by 1 in the "StockDTO" object.

For example "StockBase" has properties like Name, Owner, Color, Warranty.

While "StockDTO" has properties like Name, Owner + we want add Auto-increment-id that would give us rank of that Stock in collection starting from 1 and incremented by 1.

I read this but is there any better way to do this when mapping list to list without duplicating things in aftermap?

The only way to prevent iterating collection more than once that I could think of, would be something like this:

public class A {  }

public class B { public int Index { get;set; } }

var colA = new List<A>();
var colB = colA.Select((a, ix) => 
{
   var b = Mapper.Map<B>(a);
   b.Index = ix + 1;
   return b;
});

So, code iterates only once through the collection, and uses Mapper and its mapping profiles, in addition auto incremented property is assigned during projection.

Note: Usually, you will not use static Mapper class, rather you will use injected IMapper instance.

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