2016-06-13 9 views
1

子供がいて子どもがいるかもしれないエンティティがあります。 データベースモデルを取得すると、すべてのエンティティは正しい子と親でOKです。しかし、モデルを表示するためにマップしたいときに問題が発生します: このようなデータベースからモデルをマップする方法はありますか?同じタイプのAutomapperマップの子リスト

// database model code first 
public class Tomato 
{ 
    public int Id { get; set; } 

    public string Name { get; set; } 

    public int? ParentId { get; set; } 

    public virtual Tomato Parent { get; set; } 

    public ICollection<Tomato> Children { get; set; } 
} 

// mvc view model 
public class TomatoViewModel 
{ 
    public int Id { get; set; } 

    public string Name { get; set; } 

    public int? ParentId { get; set; } 

    public ICollection<TomatoViewModel> Children { get; set; } 
} 

configuration.CreateMap<Tomato, TomatoModel>()を設定しますが、子要素をバインドしようとすると、StackOverflowExceptionをスローします。

configuration.CreateMap<Tomato, TomatoViewModel>().ForMember(t => t.Children, 
       options => options.Condition(context => (context.SourceValue as Tomato).ParentId == this.Id)); 
// this.Id refers to TomatoViewModel.Id 

更新してみました:私のコントローラクラスで:

var models = foodIngredientsService.GetAllTomatoes().Where(t => t.ParentId == null).To<TomatoModel>().ToList(); 

2番目の質問:どのようにoptions.Condition(Func<TomatoModel, bool> func)の2番目のオーバーロードを使用するには?

答えて

1

子メンバーのマッピングを指定する場所をお試しください。

configuration.CreateMap<Tomato, TomatoViewModel>() 
.ForMember(t => t.Children, options => options.MapFrom(source => source.Children)); 
+0

'configuration.CreateMap ()'とあなたのコードとの違いは何ですか?私はこれがデフォルトの動作だと思う。 – mihkov

+0

私は試しましたが、うまくいきません。私は同じ問題に直面している。誰でもこれを回避する方法がありますか? – Sauron

+0

@Sauron私は、 'CreateMap ()'はオブジェクトを正しくマッピングし、期待通りに子コレクションを再帰的に再構成するために必要な設定です。上に掲示された私の設定は、すでに指摘されているようにデフォルトの動作です。 –

関連する問題