2

我有一个模型

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

是否可以将 AutoMapper 配置为以某种方式循环遍历我的类上的每个属性并将其映射到正确的 Entity 值。

我可以自己制作一个带有反射的转换器:

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;
 }

但是我怎样才能用 AutoMapper 的 CreateMap 实现同样的功能呢?

4

1 回答 1

1

假设您创建标记界面,例如

// marker interface
public interface ICrmBusinessObject { }

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

然后您可以定义自定义映射器函数来转换这些:

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;
      }
    });
});

你可以像这样使用映射器:

var myEntity = new MyAccount { EmailAddress1 = "me@contosco.com" };
var convertedEntity = Mapper.Map<Entity>(myEntity);
// me@contosco.com
Console.Out.WriteLine(convertedEntity["emailaddress1"]); 
于 2018-10-03T09:05:15.687 回答