简体   繁体   中英

Automapper mapping collection of enums into view model collection

  • AutoMapper 5.3.0 alpha (Yet to upgrade to the latest and greatest)

I have a DTO as follows:

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

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

and a EF POCO of:

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

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

and:

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

I need help extending my map:

CreateMap<AoACrudFieldValuesGdataHealthInput, GdataHealthTableModel>();

such that AoACrudFieldValuesGdataHealthInput.PrevHealthAssessment ends up in GdataHealthTableModel.PrevHealthAssessment. Currently I get an error as my CreateMap() is not detailed enough - naturally.

Is this possible? Or do I get the mapper to ignore that field and do it by hand?

NOTE: For both EF POCO's I have omitted the Id field which is an auto increment for sake of brevity.

Define an additional map for HealthPrevHealthAssessmentEnum -> 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));

Not sure of AutoMapper can convert an ICollection to a HashSet out of the box, I think it can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM