Automapper Object with inside list of object to primitive mapping - automapper

I'm trying to create map for automapper to let me map those entity
Entities
public class Entity
{
...
public List<NavigationEntity> Navs { get; set; }
}
public class NavigationEntity
{
public int Id { get; set; }
}
DTO that need to be create with entities
public class EntityDto
{
...
public List<int> NavIds { get; set; }
}
This doesnt seem's to do the job! What could do the job ?
CreateMap<Entity, EntityDto>().ReverseMap();
CreateMap<NavigationEntity, int>().ConstructUsing(x => x.Id);
EDIT
Tried to add
CreateMap< List < SystemsTags >, List< int >>();
but still it doesnt map

First of all, you should rename public List<NavigationEntity> Navs { get; set; } and public List<int> NavIds { get; set; } to the same name. If it is still not working try to also change ConstructUsing to ConvertUsing. And if you need the reverseMap of Entity to EntityDTO you should also add
CreateMap<int, NavigationEntity>().ConvertUsing(x => new NavigationEntity { Id = x });
final code
public class Entity
{
...
public List<NavigationEntity> Navs { get; set; }
}
public class NavigationEntity
{
public int Id { get; set; }
}
public class EntityDto
{
...
public List<int> Navs { get; set; }
}
...
CreateMap<Entity, EntityDto>().ReverseMap();
CreateMap<NavigationEntity, int>().ConvertUsing(x => x.Id);
CreateMap<int, NavigationEntity>().ConvertUsing(x => new NavigationEntity { Id = x });

Related

AutoMapper One-To-Many Filter and ProjectTo

I have the below two Entities (one-to-many)
public class ApplicationCode
{
public Guid ApplicationId { get; set; }
public string? ApplicationAcrynom { get; set; }
public int ApplicationIndex { get; set; }
public IList<ApplicationCodeTranslation> ApplicationCodeTranslations { get; private set; } = new List<ApplicationCodeTranslation>();
}
public class ApplicationCodeTranslation
{
public Guid ApplicationCodeTranslationId { get; set; }
public Guid ApplicationId { get; set; }
public Guid LanguageId { get; set; }
public string? ApplicationDescription { get; set; }
public ApplicationCode ApplicationCode { get; set; } = null!;
}
The goal is to populate the below Dto where I need to filter one language from the child list (IList ApplicationCodeTranslations) in the ApplicationCode entity to get the description value
public class ApplicationCodeDto : IMapFrom<ApplicationCode>
{
public Guid ApplicationId { get; set; }
public string? ApplicationAcrynom { get; set; }
public string? ApplicationDescription { get; set; }
public void Mapping(Profile profile)
{
profile.CreateMap<ApplicationCode, ApplicationCodeDto>();
profile.CreateMap<ApplicationCodeTranslation, ApplicationCodeDto>();
}
}
I tried below, but it does not give the intended result.
It omits the ApplicationDescription (gives null), the whole .Include line is not translated to SQL at all.
var test1 = await _context.ApplicationCodes
.Include(e => e.ApplicationCodeTranslations.Where(l => l.LanguageId == _languageId))
.ProjectTo<ApplicationCodeDto>(_mapper.ConfigurationProvider)
.ToListAsync();
The other option I tried is
var test2 = await _context.ApplicationCodes
.SelectMany(e => e.ApplicationCodeTranslations)
.Where(l => l.LanguageId == _languageId)
.ProjectTo<ApplicationCodeDto>(_mapper.ConfigurationProvider)
.ToListAsync();
Which omits the properties of the CodeApplication and brings only the child list properties, as SelectMany only brings back the props of the child.
The only way I managed to make it work is below:
var test3 = await _context.ApplicationCodes
.SelectMany(e => e.ApplicationCodeTranslations.Where(l => l.LanguageId == _languageId),
(a,t) => new ApplicationCodeDto{
ApplicationId = a.ApplicationId,
ApplicationAcrynom = a.ApplicationAcrynom,
ApplicationDescription = t.ApplicationDescription,
})
.ToListAsync();
How can AutoMapper (v.11) help in this scenario to avoid mapping the DTO props manually?
Does ProjectTo work here?

How to Map Entity Navigation Property to Dto

I am trying to map the navigation property of an Entity to a DTO without defining each property with the ForMember method.
public class OuterSource
{
public int Value { get; set; }
public InnerSource Inner { get; set; }
}
public class InnerSource
{
public int OtherValue { get; set; }
}
public class OuterDestDto
{
public int Value { get; set; }
public InnerDest Inner { get; set; }
}
public class InnerDestDto
{
public int OtherValue { get; set; }
}
cfg.CreateMap<OuterSource, OuterDest>();
cfg.CreateMap<InnerSource, InnerDest>();
Sp what I want to do is map OuterSource Entity to the InnerDestination Dto like so:
cfg.CreateMap<OuterSource, InnerDest>();
I already have the Outer and Inner Objects mapped to eachother. And I tried:
cfg.CreateMap<OuterSource, InnerDest>().IncludeMembers(s => s.InnerSource);

AutoMapper .ReverseMap() .Ignore() not working

Having an issue with version 6.1.1. In the below, the result of the reverse map still has the Company object populated. Per this post, which shows what I am doing below, except they are ignoring a property, and I'm ignoring a complex object.
What am I missing?
CreateMap<Item, ItemViewModel>(MemberList.Destination)
.ReverseMap()
.ForMember(x => x.Company, x => x.Ignore())
;
With AutoMapper 6.1 you could use ForPath instead ForMember to ignore complex objects.
See How to ignore property with ReverseMap for further information.
I see not what is wrong, but here is a running sample:
namespace AutomapperTest2
{
internal class Program
{
#region Methods
private static void Main(string[] args)
{
// Configure the mappings
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ApplicantEducation, ApplicantEducationVM>();
cfg.CreateMap<Applicant, ApplicantVM>().ReverseMap()
.ForMember(x => x.Education, x => x.Ignore());
});
var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
Applicant ap = new Applicant
{
Name = "its me",
Education =
new ApplicantEducation
{
SomeInt = 10,
SomeString = "sampleString"
}
};
// Map
ApplicantVM apVm = Mapper.Map<Applicant, ApplicantVM>(ap);
Applicant apBack = Mapper.Map<ApplicantVM, Applicant>(apVm);
}
#endregion
}
/// Your source classes
public class Applicant
{
public ApplicantEducation Education { get; set; }
public string Name { get; set; }
}
public class ApplicantEducation
{
public int SomeInt { get; set; }
public string SomeString { get; set; }
}
// Your VM classes
public class ApplicantVM
{
public string Description { get; set; }
public ApplicantEducationVM Education { get; set; }
public string Name { get; set; }
}
public class ApplicantEducationVM
{
public int SomeInt { get; set; }
public string SomeString { get; set; }
}
}
}

AutoMapper 6 - How can I create a mapping that ignore and map a list of object

I'm a little newbie on AutoMapper, I don't find almost nothing about v6.0 on Stackoverflow and Github. I need help on this problem
I have this two Entities:
public class DocFinanceiro
{
public int AutoId { get; set; }
public virtual ICollection<QuitacaoDocFinan> QuitacoesDocFinan { get; set; }
}
public class QuitacaoDocFinan
{
public int AutoId { get; set; }
public int DocFinanceiroId { get; set; }
public virtual DocFinanceiro DocFinanceiro { get; set; }
public decimal ValorTotal { get; set; }
}
}
And his ViewModels:
public class DocFinanceiroViewModel
{
public DocFinanceiroViewModel()
{
ValorPago = QuitacoesDocFinan.Where(x => x.Cancelada == false).Sum(x => x.ValorTotal);
}
public virtual ICollection<QuitacaoDocFinanViewModel> QuitacoesDocFinan { get; set; }
public decimal ValorPago { get; set; }
}
public class QuitacaoDocFinanViewModel
{
public int AutoId { get; set; }
public int DocFinanceiroId { get; set; }
public virtual DocFinanceiroViewModel DocFinanceiro { get; set; }
public decimal ValorTotal { get; set; }
}
And mapping between DocFinanceiro and DocFinanceiroViewModel:
public class DomainToViewModelMappingProfile : Profile
{
public DomainToViewModelMappingProfile()
{
CreateMap<DocFinanceiro, DocFinanceiroViewModel>().ForMember(x => x.ValorPago, y => y.Ignore())
.MaxDepth(3)
.PreserveReferences();
CreateMap<QuitacaoDocFinan, QuitacaoDocFinanViewModel>();
}
}
This mapping works when I set only one of these property
.ForMember(x => x.ValorPago, y => y.Ignore())
or
.MaxDepth(1).PreserveReferences();
, but when I try two cause an exception. I search on everywhere, but no success.
And controller where that I make the mapping:
var documentos = Mapper.Map<IEnumerable<DocFinanceiro>, IEnumerable<DocFinanceiroViewModel>>(*repository*);
Sorry if make some mistake, but I don't what to do...
You are trying to access QuitacoesDocFinan collection in DocFinanceiroViewModel constructor before initializing. Your DocFinanceiroViewModel should be something like this:
public class DocFinanceiroViewModel
{
public virtual ICollection<QuitacaoDocFinanViewModel> QuitacoesDocFinan { get; set; }
public decimal ValorPago
{
get
{
return QuitacoesDocFinan.Where(x => x.Cancelada == false).Sum(x => x.ValorTotal);
}
}
}

Automapper, Mapping one object member type to multiple concrete type

I have this Party class which contains an object data type coming from a service. It can contain two different member types for the Item property.
public class Party
{
public string DMVID {get; set;}
public object Item { get; set; }
}
and this DTO
public class PartyDTO
{
public string DMVID {get; set;}
public BusinessDTO BusinessItem { get; set; }
public IndividualDTO IndividualItem { get; set; }
}
How can I map the output of the Item to BusinessItem or IndividualItem.
I know this one would not work. Mapper.CreateMap<Party, PartyDTO>();
I don't know if conditional mapping can solve this or a resolver like this one.
Hey maybe this will help you out! I tested it, but i am using AutoMapper just for two days!
Allright here are your noted classes!!!
public class Party
{
public string DMVID { get; set; }
public object Item { get; set; }
}
public class PartyDTO
{
public string DMVID { get; set; }
public BuisnessDTO BusinessItem { get; set; }
public IndividualDTO IndividualItem { get; set; }
}
public class BuisnessDTO
{
public int Number
{
get;
set;
}
}
public class IndividualDTO
{
public string Message
{
get;
set;
}
}
and here your is the MapperConfiguration for this current scenario!
// Edit There was no need here for some conditions
AutoMapper.Mapper.CreateMap<Party, PartyDTO>()
.ForMember(dto => dto.BusinessItem, map =>
map.MapFrom(party => party.Item as BuisnessDTO);
)
.ForMember(dto => dto.IndividualItem, map =>
map.MapFrom(party => party.Item as IndividualDTO);
);
// And this is another way to achive the mapping in this scenario
AutoMapper.Mapper.CreateMap<PartyDTO, Party>()
.ForMember(party => party.Item, map => map.MapFrom( dto => (dto.BusinessItem != null) ? (dto.BusinessItem as object) : (dto.IndividualItem as object)));
And i created this sample for it!
Party firstParty = new Party()
{
DMVID = "something",
Item = new BuisnessDTO()
{
Number = 1
}
};
Party secondParty = new Party()
{
DMVID = "something",
Item = new IndividualDTO()
{
Message = "message"
}
};
PartyDTO dtoWithBuisness = AutoMapper.Mapper.Map<PartyDTO>(firstParty);
PartyDTO dtoWithIndividual = AutoMapper.Mapper.Map < PartyDTO>(secondParty);
Party afterParty = AutoMapper.Mapper.Map<Party>(dtoWithBuisness);
afterParty = AutoMapper.Mapper.Map < Party>(dtoWithIndividual);
Of course there are other possibility, but I think thats exactly what you wanted.

Resources