0

I met today with strange behavior of AutoMapper library. Why string.Format in the second case does not work? Are you able to explain to me why the first case works when the second throwing an exception?


Mapping configuration: (working)

config.CreateMap<Person, PersonView>().
    ForMember(dest => dest.FullName, opt => opt.
       MapFrom(src => src.Data.Code + " - " + src.Number));

Mapping configuration: (not working)

config.CreateMap<Person, PersonView>().
    ForMember(dest => dest.FullName, opt => opt.
        MapFrom(src => string.Format("{0} - {1}", src.Data.Code, src.Number)));

Projection:

using (var ctx = new MyDbContext())
{
    return ctx.Persons.Include(i => i.Data).Project().To<PersonView>().ToList();
}

Exception:

enter image description here

Pawel Maga
  • 5,428
  • 3
  • 38
  • 62
  • Possible duplicate of [LINQ to Entities does not recognize the method 'System.String ToString()' method in MVC 4](http://stackoverflow.com/questions/18233495/linq-to-entities-does-not-recognize-the-method-system-string-tostring-method) – Andrew Savinykh Oct 15 '15 at 20:07
  • SO is literally full of questions like this one. Did you search? [One](http://stackoverflow.com/questions/7259567/linq-to-entities-does-not-recognize-the-method) [Two](http://stackoverflow.com/questions/32337856/linq-cannot-understand-when-converting-a-method-to-a-string) [Three](http://stackoverflow.com/questions/18233495/linq-to-entities-does-not-recognize-the-method-system-string-tostring-method) [Four](http://stackoverflow.com/questions/10079990/linq-to-entities-does-not-recognize-the-method-system-string-formatsystem-stri) – Andrew Savinykh Oct 15 '15 at 20:08
  • And Charles is right it does not appear to have anything to do with Automapper. – Andrew Savinykh Oct 15 '15 at 20:09

1 Answers1

4

It's not really anything to do with AutoMapper.

You're effectively asking Entity Framework to translate an expression that calls a method (string.Format in this case) into SQL. It can't do that.

The first works because it's a simple string concatenation, which is more readily translated.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45