3

I am trying to map an Entity Framework model to a view model after saving.

//Map my incoming VM to a DTO and save it
Inquiry savedInquiry = InquiryLogic.Save(mapper.Map<InquirySpec>(inquiryVM));

//Map the returned Inquiry back to a VM and return it
return mapper.Map<JournalEntryInquiryVM>(savedInquiry);

I can map an Inquiry to a JournalEntryInquiryVM successfully, but when I try to map savedInquiry back to a JournalEntryInquiryVM, I get the following exception because it's not actually just an Inquiry, it's a Dynamic Proxy created by Entity Framework:

Missing type map configuration or unsupported mapping.

Mapping types: Inquiry_66DF1FFF68CAC6E17FC0F72D753A523B9CCF3AFA55E82C2B5B910A95B0BFCC79 -> JournalEntryInquiryVM System.Data.Entity.DynamicProxies.Inquiry_66DF1FFF68CAC6E17FC0F72D753A523B9CCF3AFA55E82C2B5B910A95B0BFCC79 -> TLGI.CRM.MVCWeb.ViewModels.CustomerAccounts.JournalEntryInquiryVM

At this point in the code, my DbContext is already disposed and I've retrieved any Navigation Properties I need. I just need it to do the mapping as if it were just an Inquiry.

It looks like this was possible in old versions of AutoMapper, but I can't find anything on StackOverflow or the Automapper wiki with an answer for version 6.1.1 (which is what I'm using) or later. AutoMapper changes so much it's hard to ever find anything relevant.

xr280xr
  • 12,621
  • 7
  • 81
  • 125

1 Answers1

0

Use AutoMapper's IQueryable Extention

  1. If you would like to get DTOs from proxies queryable:

    mapper.ProjectTo<TDest>(sourceQueryable) will help you.

  2. If you would like to get DTO object from a proxy entity:

    mapper.ProjectTo<TDest>(new[] { source }.AsQueryable()).Single()

In your case, the JournalEntryInquiryVM is TDest, savedInquiry is source.

Péter Hidvégi
  • 743
  • 6
  • 21