自动映射将枚举的集合映射到视图模型集合中

时间:2017-04-06 10:43:07

标签: c# automapper

  • AutoMapper 5.3.0 alpha(尚未升级到最新且最好的)

我有一个DTO如下:

   <div class="row">
  <div class="col-sm-4">
   <div class="clearfix content-heading">
    <img src="http://lorempixel.com/300/200/" class="pull-left img-rounded" style="margin-right:10px;width:100px;height:100px;">
    <h3>Header 1</h3>
    <p>Text 1 is cool text</p>
    </div>
  </div>
  <div class="col-sm-4">
  <div class="clearfix content-heading">
    <img src="http://lorempixel.com/400/200/" class="pull-left img-rounded" style="margin-right:10px;width:100px;height:100px;">
    <h3>Header 2</h3>
    <p>Text 2 is also cool text</p>
    </div>
  </div>
    <div class="col-sm-4">
    <div class="clearfix content-heading">
    <img src="http://lorempixel.com/800/800/" class="pull-left img-rounded" style="margin-right:10px;width:100px;height:100px;">
    <h3>Header 3</h3>
    <p>Text 3 is also very cool text</p>
    </div>
  </div>
</div>

和EF POCO:

public class AoACrudFieldValuesGdataHealthInput
{
    public AoACrudFieldValuesGdataHealthInput()
    {
       PrevHealthAssessment = new HashSet<HealthPrevHealthAssessmentEnum>();
    }

    public HashSet<HealthPrevHealthAssessmentEnum> PrevHealthAssessment { get; set; }
}

[Table("Health", Schema = "gdata")]
public class GdataHealthTableModel : AuditedEntity
{
    public GdataHealthTableModel()
    {
        //PrevHealthAssessment = new HashSet<HealthPrevHealthAssessmentEnum>();
    }

    [ForeignKey("Id")]
    public ICollection<GdataHealthPrevAssesmentTableModel> PrevHealthAssessment { get; set; }
}

我需要帮助扩展我的地图:

[Table("HealthPrevAssesment", Schema = "gdata")]
public class GdataHealthPrevAssesmentTableModel : AuditedEntity
{
    public HealthPrevHealthAssessmentEnum Assessment { get; set; }
}

这样AoACrudFieldValuesGdataHealthInput.PrevHealthAssessment最终会在GdataHealthTableModel.PrevHealthAssessment中结束。目前我收到一个错误,因为我的CreateMap()不够详细 - 当然。

这可能吗?或者我是否让映射器忽略该字段并手动完成?

注意:对于两个EF POCO,我省略了Id字段,为了简洁起见,这是一个自动增量。

1 个答案:

答案 0 :(得分:0)

HealthPrevHealthAssessmentEnum定义其他地图 - &gt; GdataHealthPrevAssesmentTableModel

CreateMap<AoACrudFieldValuesGdataHealthInput, GdataHealthTableModel>()
    .ForMember(dest => dest.PrevHealthAssessment, o => o.MapFrom(src => src.PrevHealthAssessment));

CreateMap<HealthPrevHealthAssessmentEnum, GdataHealthPrevAssesmentTableModel>()
    .ForMember(dest => dest.Id, o => o.Ignore()) // auto ID
    .ForMember(dest => dest.Assessment , o => o.MapFrom(src => src));

不确定AutoMapper是否可以将ICollection转换为开箱即用的HashSet,我认为可以。