Search code examples
c#dynamics-crmautomappercrmxrm

How to create a map from model to Entity, and Entity to model, with AutoMapper?


I have a model

class Account 
{
    public string Name { get; set; }
    public string EmailAddress1 { get; set; }
}

Is it possible to configure AutoMapper to somehow loop through each property on my class and map it to the correct Entity value.

I am able to make a converter with reflection myself:

public Entity ConvertToEntity()
{
    var propertyDict = typeof(Account).GetProperties()
      .Select(x => new KeyValuePair<string, object>(x.Name, x.GetValue(typeof(Account))));
    var entity = new Entity();

    foreach (var prop in propertyDict) t[prop.Key] = prop.Value;

    return entity;
 }

But how can i achieve the same kind of functionality with AutoMapper's CreateMap?


Solution

  • Suppose you create marker interface like

    // marker interface
    public interface ICrmBusinessObject { }
    
    public class MyAccount : ICrmBusinessObject
    {
      public string EmailAddress1 { get; set; }
    }
    

    Then you can define custom mapper function to convert those:

    Mapper.Initialize(cfg => {
      cfg.CreateMap<ICrmBusinessObject, Entity>()
        .AfterMap((crmEntity, entity) =>
        {
          var type = crmEntity.GetType();
          var propertyDict = type.GetProperties()
            .Select(x => new KeyValuePair<string, object>(x.Name.ToLowerInvariant(),
              x.GetValue(crmEntity)));
    
          foreach (var prop in propertyDict)
          {
            entity[prop.Key] = prop.Value;
          }
        });
    });
    

    And you can use mapper like:

    var myEntity = new MyAccount { EmailAddress1 = "me@contosco.com" };
    var convertedEntity = Mapper.Map<Entity>(myEntity);
    // me@contosco.com
    Console.Out.WriteLine(convertedEntity["emailaddress1"]);