1

We are designing a temporal system where the definition of an entity can change. I am trying to setup Automapper but can't quite work out how the prefix should work.

As an example, I would have the following entity:

public class ReferenceDataDefinition
{
    public string Name { get; set; }
}

public class ReferenceData 
{
    public int Id { get; set; }
    public ReferenceDataDefinition Current { get; set; }
}

With the following DTO:

public class ReferenceDataDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I know I can use

CreateMap<ReferenceData, ReferenceDataDTO>()
    .ForMember(p => p.Id, o => o.MapFrom(s => s.Id)
    .ForMember(p => p.Name, o => o.MapFrom(s => s.Current.Name);

But I feel there must be something smarter I can do? I've tried adding RecognizePrefixes("Current") but that had no effect.

ciantrius
  • 683
  • 1
  • 6
  • 21

2 Answers2

1

I've tried adding RecognizePrefixes("Current")

This isn't how prefix are used. They are for a scenario where your properties start with a prefix (often because of a database naming schema).

For example, If you had the following classes:

public class ReferenceData 
{
    public int Ref_Id { get; set; }
    public string Ref_Name { get; set; }
}

public class ReferenceDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

You could recognize the following prefix:

cfg.RecognizePrefixes("Ref_");

AutoMapper would then be able to map those two objects without you having to define specific mappings with .ForMember.

Regarding you own mapping, since both Id properties on ReferenceData and ReferenceDataDTO have the same name, you should be able to remove the Id member mapping as AutoMapper can infer it automatically:

CreateMap<ReferenceData, ReferenceDataDTO>()
    .ForMember(p => p.Name, o => o.MapFrom(s => s.Current.Name);

This should suffice.

As for .Current using Flattening you could remove it if you would change your DTO class to rename it to CurrentName.

Gilles
  • 5,269
  • 4
  • 34
  • 66
0

Please check this documentation: Recognizing pre/postfixes Also the RecognizePrefixes works for source object prefixes Use RecognizeDestinationPrefixes method

Check these previous posts: AutoMapper with prefix https://github.com/AutoMapper/AutoMapper/issues/421

Community
  • 1
  • 1
slipknot
  • 46
  • 6