Home > database >  Configure globally property types mapping for all models using Mapster
Configure globally property types mapping for all models using Mapster

Time:07-05

I have a LocalizedString struct with a GetCurrentLocalization() method and I want to call it when map an Entity to a DTO (so I don't have to do it manually). And ideally, do not manually configure mappings every time, but write a global config once so that all LocalizedStrings are automatically mapped to a string.

This is what my entity looks like:

public class TeaEntity : IEntity
{
    public Guid Id { get; init; }
    public LocalizedString Name { get; init; }
}

And so DTO:

public class TeaDto : IDto
{
    public Guid Id { get; init; }
    public string Name { get; init; }
}

Mapster config (it doesn't work, the ToString() method is called on LocalizedString instead):

config.ForType<LocalizedString, string>().Map(
        rawString => (LocalizedString)rawString,
        localized => localized.GetCurrentLocalization());

P.S. I don't think it makes sense to show the LocalizedString structure (but if this information is not enough, I can add it).

CodePudding user response:

Okay, everything turned out to be much easier :)

config.NewConfig<LocalizedString, string>().MapWith(
    localized => localized.GetCurrentLocalization());
config.NewConfig<string, LocalizedString>().MapWith(
    rawString => (LocalizedString)rawString);
  • Related