1

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?

muttley91
  • 12,278
  • 33
  • 106
  • 160
  • Do you get any more information on the stack of the exception? This would be tremendously helpful for source code inspection! –  May 20 '15 at 20:13
  • 3
    This works fine in a simple example: https://dotnetfiddle.net/lA83xE – Andrew Whitaker May 20 '15 at 20:14
  • What version of AutoMapper are you using? – Jimmy Bogard May 20 '15 at 21:12
  • I'm using Version 3.1.1 – muttley91 May 20 '15 at 21:23
  • I am using nuget package using AutoMapper.Mapper.CreateMap().ConvertUsing(source => source.Name); then AutoMapper.Mapper.CreateMap().ForMember(dest => dest.Brands, opts => opts.MapFrom(src => src.Brands)) error when calling prospects = db.Prospects.ProjectTo().ToList(); On ProspectDTO the Brands are public IEnumerable Brands { get; set; } – MemeDeveloper Nov 19 '15 at 22:57
  • I see stack : System.Linq.Expressions.Expression.New(Type type) +3792767 AutoMapper.TypeMap.DestinationConstructorExpression(Expression instanceParameter) +231 AutoMapper.MappingEngine.CreateMapExpression(ExpressionRequest request, Expression instanceParameter, IDictionary`2 typePairCount) +250 – MemeDeveloper Nov 19 '15 at 22:58
  • seems my use case just may not be possible with ProjectTo as per jimmy boggard comments here https://groups.google.com/forum/#!topic/automapper-users/xYRFsIY3Q1w – MemeDeveloper Nov 20 '15 at 00:33

1 Answers1

2

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 !!!

MemeDeveloper
  • 6,457
  • 2
  • 42
  • 58