4

I try to move my project to AutoMapper 9.x but I don't find a solution to update an object read from EF.

The situation is like as describe on this old post Using Automapper to update an existing Entity POCO

The big issue is that: AutoMapper 9.x has removed the static Mapper.Map and you can add the [AutoMap(typeof(x))] attribute but it solve the mapping from EF Class to DTO class.

class MyPoco{
    public int Id {get;set;}
}

[AutoMap(typeof(MyPoco))]
public class Customer {
    public int Id { get;set; }
}

    MYPOCO pocoDesc= dbContext.DD_POCO.SingleOrDefault(m => m.Id == 123);
    //Row below not supported
    AutoMapper.Mapper.Map<Customer, MYPOCO>(customerSrc, pocoDesc);
    dbContext.Save();

At the moment the only way to solve is remove AutoMapper and manually bind one by one the property.

UPDATE

After some test I try to compare to call

ObjectMapper.Map(input.Article, article);
        Mapper.Instance.Map(input.Article, article);

ObjectMapper came from DI. In startup module I register via IMapperConfigurationExpression

    mapper.CreateMap<Customer,MyPoco>().ConvertUsing((src,dto) =>{
// remove for brevity
});

And I see that static API not pass throw my custom map opposite to ObjectMapper that use my custom map. At the moment I don't understand why but I try to investigate more

andmattia
  • 357
  • 6
  • 22
  • 3
    Rather than use the static Mapper.Map, the preferred way is to use Dependency Injection and inject the Mapper in to services that need it. – phuzi Aug 13 '19 at 08:03
  • Static mappings where never needed to map EF classes. Just inject the mapper instance, the same way you inject the `dbContext`, or create your own singleton instance of the mapper, eg `static class MyMapper{ static MyMapper(){/*initialize here*/} public static Mapper {get; private set;} }`. The *correct* solution though is to use dependency injection – Panagiotis Kanavos Aug 13 '19 at 08:07
  • What does your code look like, specifically the methods that use the mapper and their classes? How do you pass dependencies to them? If you want a specific answer this matters. In an .NET Core project for example, DI is a standard feature. In ASP.NET MVC the code you'd need to inject the mapper depends on the actual DI container you use. – Panagiotis Kanavos Aug 13 '19 at 08:11
  • My project is based on Asp.net Boilerplate v 4.8.1 (and the framework use Castle for DI). So if I correct understand the suggestion is use IMapper inject via DI (in my case I can use ObjectMapper that do exact via DI) in place of Mapper.Map? – andmattia Aug 13 '19 at 08:17
  • That's the idea :) – Lucian Bargaoanu Aug 13 '19 at 10:04
  • @LucianBargaoanu thanks for the clarification – andmattia Aug 13 '19 at 14:32

0 Answers0