3

I have two classes :

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Product Product { get; set; }
}

public class Product
{
    public int ProductNumber { get; set; }

    public string ProductColor { get; set; }
}


public class Customer_
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Article Article { get; set; }
}

public class Article
{
    public int ArticleNumber { get; set; }

    public string ArticleColor { get; set; }
}

And one instance :

Customer Cus = new Customer()
{
    FirstName = "FirstName1",
    LastName = "LastName1",
    Product = new Product()
    {
        ProductColor = "ProductColor1",
        ProductNumber = 11
    }
};

I want to create one instance of class Customer_ from my instance Cus

I use Automapper :

MapperConfiguration Config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Customer, Customer_>()
    .ForMember(a => a.Article, b => b.MapFrom(c => c.Product));

    cfg.CreateMap<Product, Article>()
    .ForMember(a => a.ArticleColor, b => b.MapFrom(c => c.ProductColor))
    .ForMember(a => a.ArticleNumber, b => b.MapFrom(c => c.ProductNumber));                
});

IMapper Mapper = Config.CreateMapper();
var cus_ = Mapper.Map<Customer, Customer_>(Cus);

Its works but I want to create the MapperConfiguration from a configuration file. Like this :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <Automapper>
    <Column source="Product" destination="Article"/>
    <Column source="Product.ProductColor" destination="Article.ArticleColor"/>
    ...
    ...
    ...
  </Automapper>
</configuration>

Is it possible ?

Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76

1 Answers1

4

There's no way to do this out of the box with AutoMapper, but with the type-based version of AutoMapper, you can certainly do this:

cfg.CreateMap(typeof(Customer), typeof(Customer_))
    .ForMember("Product").MapFrom("Article");

So you'd just need to loop through your XML, load up the types, and for each sub-node, call MapFrom for the two strings you have.

Your XML doesn't look quite complete enough to do this, you'd need to have something like:

<TypeMap SourceType="Customer" DestinationType="Customer_">
    <PropertyMap Member="Product" MapFrom="Article">
</TypeMap>

etc.

Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69