Automapper-Map to a string

1.6k Views Asked by At

I tried creating a mapping to a string using the following CreateMap():

Mapper.CreateMap<MyComplexType, string>()
    .ConvertUsing(c => c.Name);

But when I try to use this mapping, I get the following error:

Type 'System.String' does not have a default constructor

That makes sense, but I've been reading around and supposedly this should work. Is there something else I have to do?

1

There are 1 best solutions below

0
On

In my case I was using

.ProjectTo<>()

To project directly from a DBContext collection (EF 6) to my DTO e.g.

db.Configuration.LazyLoadingEnabled = false;
prospects = db.Prospects.Where([my where lambda]).ProjectTo<ProspectDTO>().ToList();

With a destination with an IEnumerable<string> property coming from a M-M related table i.e.

public class ProspectDTO 
{
   public IEnumerable<string> Brands { get; set; }
}

and my solution was mapping as follows

AutoMapper.Mapper.CreateMap<Prospect, ProspectDTO>().ForMember(dest => dest.Brands, opts => opts.MapFrom(src => src.Brands.Select(b => b.Name)));

N.B. I am using the ProjectTo<> like this to avoid the common lazy loading select n+1 problem and ensure decent (quick) sql runs against the DB, and I have all the related table data I need. Excellent.

Thanks Jimmy Bogard you rockstar !!!