Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper with prefix

Tags:

c#

automapper

I'm trying to use Automapper to map to objects, the issue is one of the objects I'm trying to map has a prefix 'Cust_' in front of all its properties and one doesn't. Is there a way to make this mapping.

For example say I have

class A
{
      String FirstName { get; set; }
      String LastName { get; set; }
}

class B
{
      String Cust_FirstName { get; set; }
      String Cust_LastName { get; set; }
}

Obviously this map won't work

AutoMapper.Mapper.CreateMap<A, B>();
b = AutoMapper.Mapper.Map<A, B>(a);
like image 787
Cliff Mayson Avatar asked Feb 17 '12 00:02

Cliff Mayson


People also ask

When should I use AutoMapper?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.

Where do I configure AutoMapper?

The MapperConfiguration instance can be stored statically, in a static field or in a dependency injection container. Once created it cannot be changed/modified. var configuration = new MapperConfiguration(cfg => { cfg. CreateMap<Foo, Bar>(); cfg.

What is an AutoMapper?

AutoMapper is a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types. As an example, you might need to map the DTOs (Data Transfer Objects) in your application to the model objects.


1 Answers

Mapper.Initialize(cfg =>
{
   cfg.RecognizeDestinationPrefixes("Cust_");
   cfg.CreateMap<A, B>();
});

A a = new A() {FirstName = "Cliff", LastName = "Mayson"};
B b = Mapper.Map<A, B>(a);

//b.Cust_FirstName is "Cliff"
//b.Cust_LastName is "Mayson"

Or alternatively:

Mapper.Configuration.RecognizeDestinationPrefixes("Cust_");
Mapper.CreateMap<A, B>();
...
B b = Mapper.Map<A, B>(a);
...
like image 153
Pero P. Avatar answered Sep 20 '22 16:09

Pero P.