如何使用Automapper展平C#中反复使用的子对象

时间:2019-01-14 15:43:30

标签: c# automapper

使用以下实体

public class User
{
    public Guid Id { get; set; }
    public string Username { get; set; }
}

public class GeneralEntity
{
    public Guid Id { get; set; }

    public User CreatedByUser { get; set; }

    public User DeletedByUser { get; set; }
}

如何将其展平到下面的GeneralEntityDto?

public class GeneralEntityDto
{
    public Guid Id { get; set; }

    public string CreatedByUsername { get; set; }

    public string DeletedByUsername { get; set; }
}

我尝试按如下所示设置映射,但由于未映射“ CreatedByUsername”和“ DeletedByUsername”而失败。

protected void Configure()
{
    CreateMap<GeneralEntity, GeneralEntityDto>()
        .ForMember(dest => dest.CreatedByUsername, 
            opt => opt.MapFrom(src => src.CreatedByUser.Username))
        .ForMember(dest => dest.DeletedByUsername, opt => 
            opt.MapFrom(src => src.DeletedByUser.Username));
}

1 个答案:

答案 0 :(得分:1)

您可以使用自动映射器提供的命名约定。 基本上,如果您包含源对象的属性名称的确切字符串,则不必添加ForMember() automapper足够聪明,可以自动执行此操作。

这表示例如:

public class GeneralEntity
{
  public Guid Id { get; set; }

  public User CreatedBy { get; set; } // renaming just for simplicity

  public User DeletedBy { get; set; } // renaming just for simplicity
}



public class GeneralEntityDto
{
  public Guid Id { get; set; }

  public string CreatedByUsername { get; set; }

  public string DeletedByUsername { get; set; }
}

还请参考以下内容:

http://docs.automapper.org/en/stable/Flattening.html

AutoMapper TwoWay Mapping with same Property Name