1

I have a domain model that contains member variables for two languages, something like this:

public class Resource
{
   public string SwedishName;
   public string EnglishName;
}

For presentation I have a simplified model, that is delivered to a json serializer:

[JsonObject]
public class JsonResource
{
   [JsonProperty]
   public string Name;
}

These are mapped with automapper like so:

Mapper.CreateMap<Resource, JsonResource>()
    .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.SwedishName));

My question is, if this is possible to do in a more conditional way, depending on which language is asked for? My initial thought, was something along these lines:

string lang = "en";
json = Mapper.Map<Resource, JsonResource>(resource, lang)

Though, it does not seem possible to have several mappings for the same types?

Currently Im leaning towards, just defining another identical presentation model for the other language:

if (lang == "en")
    json = Mapper.Map<Resource, EnglishJsonResource>(resource)
else
    json = Mapper.Map<Resource, JsonResource>(resource)

Is this a feasible solution, or is there a better way?

4

2 に答える 2

4

私は別のクラスを作成しません。使用AfterMap:

Mapper.CreateMap<Resource, JsonResource>()
 .AfterMap((r,b) => r.Name = isEnglish ? b.EnglishName : b.SwedishName);

isEnglishはアプリの条件ですが、使用する必要があります。

于 2012-04-17T10:14:03.250 に答える
0

たとえば、メソッド initMapping を使用して IMapper インターフェイスを実装する 2 つの異なるクラス EngMapper と SimpleMapper を作成できます。その後、言語に応じて適切なマッパーを取得するためにファクトリを作成できます。したがって、最終的には、マッピングはさまざまな言語で分離されます (私の意見では、これがより良い方法です)。

于 2012-04-17T10:12:28.590 に答える