Question

I'm new to Automapper and have been able to work through most of the mapping errors in the past except this one.

I'm getting an error in my (HTTPGET) Edit controller method when I map the CaseInfo entity to the CaseInfoEdit view model that said I have some invalid arguments on the line of code below.

var vModel = Mapper.Map<CaseInfo, CaseInfoEditViewModel>(editCase);

This mapping issue started after I included the Attorney entity being returned with this CaseInfoRepository.Get() statement. The CaseInfo results of this query are being returned correctly with the Attorney reference object.

var editCase = unitOfWork.CaseInfoRepository.Get(c => c.CaseInfoID == id, includeProperties: "Attorney");

The view model has a foreign key AttorneyId and an Attorney reference property, which is why the mapping is failing I believe. Both the CaseInfo Entity and the CaseInfoViewModel are exactly the same.

public class CaseInfoEditViewModel
{
    public int CaseInfoID { get; set; }

    // a bunch of property sets and gets ...

    public int AttorneyId { get; set; }
    public virtual Attorney Attorney { get; set; }

In an attempt to correct the mapping I added a ForMember setting the source and destination to the Attorney reference property, which did not help the mapping problem. Any help with the correct way to map a reference property would be appreciated.

Mapper.CreateMap<CaseInfoEditViewModel, CaseInfo>()
              .ForMember(dst => dst.AttorneyId, opt => opt.MapFrom(src => src.AttorneyId))
              .ForMember(dst => dst.Attorney, opt => opt.MapFrom(src => src.Attorney))
              .ForMember(dst => dst.CaseInfoID, opt => opt.Ignore());
Was it helpful?

Solution

I have figured out the problem, which was not how I mapped the Attorney member within CreateMap it was correct. My get statement was returning a IEnumerable list which was incorrect. I changed the way I queried the data like so, which returns a single entity and the mapping issue was corrected.

var editCase = unitOfWork.CaseInfoRepository.GetByID(id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top