Map a property to list of object using AutoMapper CreateMap
You can create a class which implements ITypeConverter< OrderDtoList, List > and create the mapping using ConvertUsing method.
public class OrderDtoListMapper : ITypeConverter<OrderDtoList, List<Order>>
{
public List<Order> Convert(OrderDtoList source, List<Order> destination, ResolutionContext context)
{
return context.Mapper.Map<List<Order>>(source.Orders);
}
}
Then, you can create your mapping like this:
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<OrderDto, Order>();
CreateMap<OrderDtoList, List<Order>>().ConvertUsing<OrderDtoListMapper>();
}
}
Hope this is what you were looking for!
mapping list of objects using automapper
Remove the List
mappings.
CreateMap<List<Car>, List<CarVM>>();
CreateMap<List<CarVM>, List<Car>>();
You only need the singular mappings.
The plural/list ones come out-of-the-box, see the documentation.
CreateMap<Car, CarVM>();
CreateMap<CarVM, Car>();
You probably also meant: mapper.Map<List<CarVM>>(cars)
.
Automapper - Map list of string to list of object with string property
You need to use ConvertUsing
and add a map from ImportantListClass
to string
:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Second, First>();
cfg.CreateMap<ImportantListClass, string>()
.ConvertUsing(source => source.Name);
});
var mapper = config.CreateMapper();
var second = new Second
{
Id = 22,
ImportantList = new List<ImportantListClass>
{
new ImportantListClass { Name = "Name1" },
new ImportantListClass { Name = "Name2" }
}
};
var first = mapper.Map<First>(second);
Automapper: Map property in list of objects
You should use the AfterMap
function to do some postprocessing on the mapped items.
There are two ways to go about this. One is using something statically defined in the mapping profile. But in your case, you have something that's dynamic at runtime, like the ExternalId
. Doing the aftermap in your AccountService
then makes perfect sense.
I've found these kind of constructions very useful, especially when I want to consult other injected services for additional information.
public void AddExternalAccounts(Guid externalId, List<ExternalAccountDto> accounts)
{
var entities = _mapper.Map<List<ExternalAccountDto>, List<Account>>(accounts,
options => options.AfterMap((source, destination) =>
{
destination.ForEach(account => account.ExternalId = externalId);
}));
}
Two more cents regarding the AccountProfile
class:
You can check upon creation of the mapping profile if the mapping profile is correct. This will save you a headache running into this problem later at runtime. You'll know immediately that there is a problem with the configuration.
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<MappingProfile>();
cfg.AllowNullDestinationValues = false;
});
// Check that there are no issues with this configuration, which we'll encounter eventually at runtime.
config.AssertConfigurationIsValid();
_mapper = config.CreateMapper();
This also notified me that an .Ignore()
on the ExternalId
member of the Account
class was required:
CreateMap<ExternalAccountDto, Account>().ForMember(d => d.ExternalId, a => a.Ignore());
Automapper - map list of complex object to list of properties
You just provide the Mapping from MyDomainObj
to MyDto
, and it should be able to handle mapping the collections:
Mapper.CreateMap<MyDomainObj,MyDTO>()
.ForMember(d => d.custId, o => o.MapFrom(s => s.customer.customer_id))
.ForMember(d => d.orderId, o => o.MapFrom(s => s.order.order_id));
Then call it just like you had (assuming myDomainObj
is a List<MyDominObj>
):
var response = Mapper.Map<List<MyDomainObj>, List<MyDTO>>(myDomainObjList);
Automapper: Mapping an object to a LIST
static version of CreateMap
is removed: AutoMapper.Mapper does not contain definition for CreateMap
I do not know whether you have choice of upgrading. But with latest AutoMapper
(10.1.1), following code works (you did not give the completed code so I created object of SupportedCurrencies
)
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Currency, SupportedCurrency>()
.ForMember(p => p.MinAmount, q => q.MapFrom(r => r.AmountMin))
.ForMember(p => p.MaxAmount, q => q.MapFrom(r => r.AmountMax))
.ForMember(p => p.CurrencyCode, q => q.MapFrom(r => r.Code));
});
SupportedCurrencies supportedCurrencies = new SupportedCurrencies();
IMapper mapper = config.CreateMapper();
mapper.Map<IList<SupportedCurrency>>(supportedCurrencies);
Access a property of a list when using CreateMap with automapper
You can just do a map of single objects and AutoMapper will handle the lists cases as well.
x.CreateMap<CouponCsvItem, Coupon>()
.ConvertUsing(x => x.SchoolType, opt => opt.MapFrom(new SchoolResolver()));
Related Topics
Error Reading Jobject from Jsonreader. Current Jsonreader Item Is Not an Object: Startarray. Path
Make a File Open in Browser Instead of Downloading It
How to Return a File (Filecontentresult) in ASP.NET Webapi
Merge Multiple Lists into One List With Linq
Posting Jsonobject With Httpclient from Web API
How to Use Telegram API in C# to Send a Message
How to Set Autoincrement Ids in Unit Test
C# Best Way to Run a Function Every Second, Timer VS Thread
How to Upload File to Server With Http Post Multipart/Form-Data
Asp.Net Core Identity Successful Login Redirecting Back to Login Page
How to Calculate Sum (Total) of Datatable Columns Using C#
Read and Parse a Json File in C#
How to Check If a Socket Is Connected/Disconnected in C#
How to Store List of Data from Database to Arraylist or List in C#
Returning a File to View/Download in ASP.NET MVC
Copy Few Items from One List to Another List of Same Type in C#