15

シンプルな MVC4 アプリケーションを作成しています

私はオートマッパーを持っています

 Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Stringphoneno));

IntphoneNoは DataType intです (IntphoneNo は私のクラスの変数ですPerson) ソース属性Stringphonenoは Datatype stringです。

マッピングすると、次のエラーが発生します。

タイプ 'AutoMapper.AutoMapperMappingException' の例外が AutoMapper.dll で発生しましたが、ユーザー コードで処理されませんでした

しかし、IntphoneNo のDatatypeintからstringに変更する と、プログラムは正常に実行されます。

残念ながら、モデルのデータ型を変更できません

マッピングでDatatupeを変更する方法はありますか..以下のようなもの

.ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Int32(Stringphoneno));

いくつかの調査の後、私は一歩進んだ..
私のStringPhoneNoが= 123456の場合、次の
コードが機能しています。文字列に解析する必要はありません

Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Stringphoneno));

しかし、私の StringPhoneNo が = 12 3456 ( 12 の後にスペースがある) の場合、私のコードは機能しません。automapperで Stringphoneno (Web サービスから取得している Stringphoneno) のスペースをトリミングする方法はありますか。

以下のようなもの..

Mapper.CreateMap<SourceClass, DestinationClass>()
      .ForMember(dest => dest.IntphoneNo, 
                  opt => opt.MapFrom(src => src.Trim(Stringphoneno))); 
4

4 に答える 4

22
Mapper.CreateMap<SourceClass, DestinationClass>() 
    .ForMember(dest => dest.IntphoneNo, 
        opt => opt.MapFrom(src => int.Parse(src.Stringphoneno)));

説明したマップを使用した作業コードのサンプルを次に示します。

class SourceClass
{
    public string Stringphoneno { get; set; }
}

class DestinationClass
{
    public int IntphoneNo { get; set; }
}

var source = new SourceClass {Stringphoneno = "8675309"};
var destination = Mapper.Map<SourceClass, DestinationClass>(source);

Console.WriteLine(destination.IntphoneNo); //8675309
于 2013-09-12T14:46:58.050 に答える
12

直面する可能性のある問題は、文字列を解析できない場合です。1 つのオプションは、ResolveUsing を使用することです。

Mapper.CreateMap<SourceClass, DestinationClass>() 
.ForMember(dest => dest.intphoneno, opts => opts.ResolveUsing(src =>
                double.TryParse(src.strphoneno, out var phoneNo) ? phoneNo : default(double)));
于 2017-02-26T21:06:47.537 に答える