Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper : Copy IList<> to IList<>

Tags:

c#

automapper

I have an IList<AdminVAT> and I'd like to copy this collection to IList<AdminVATDto> collection

I tried this :

IList<AdminVAT> listAdminVAT = new AdministrationService(session).ListDecimal<AdminVAT>();
AutoMapper.Mapper.CreateMap<IList<AdminVAT>, List<AdminVATDTO>>();
var res = AutoMapper.Mapper.Map<IList<AdminVAT>, IList<AdminVATDTO>>(listAdminVAT);

I receive this exception :

Trying to map System.Collections.Generic.IList`1[[AdminVAT, eSIT.GC.DataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.IList`1[[AdminVATDTO, eSIT.GC.WebUI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].

Thanks.

Update1

public class AdminVAT : IAdminDecimal
{
    public virtual int Id { get; set; }
    public virtual int Code { get; set; }
    public virtual decimal Value { get; set; }
}
public class AdminVATDTO : AdminVAT
{
    [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
    public override decimal Value { get; set; }
}

I still have 5 decimal in my dropdown list ...

Controller :

IList<AdminVAT> listAdminVAT = new AdministrationService(session).ListDecimal<AdminVAT>();
AutoMapper.Mapper.CreateMap<AdminVAT, AdminVATDTO>();
model.ListVAT = AutoMapper.Mapper.Map<IList<AdminVAT>, IList<AdminVATDTO>>(listAdminVAT);

HTML :

@Html.DropDownList("ddVAT", new SelectList(Model.ListVAT, "Id", "Value", Model.Estimation.AdminVAT))
like image 282
Kris-I Avatar asked Jun 17 '11 11:06

Kris-I


People also ask

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

How do I ignore source property AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

Where is AutoMapper configuration?

Where do I configure AutoMapper? ¶ Configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.


1 Answers

Define the mapping only between the simple types as explained in the documentation:

AutoMapper.Mapper.CreateMap<AdminVAT, AdminVATDTO>();

Then you will be able to convert between lists, collections, enumerables of those types:

IList<AdminVATDTO> res = AutoMapper.Mapper.Map<IList<AdminVAT>, IList<AdminVATDTO>>(listAdminVAT);
like image 192
Darin Dimitrov Avatar answered Sep 25 '22 01:09

Darin Dimitrov