2011-03-12 97 views
0

幫助我有兩個類,如下所示:需要與AutoMapper

public class Rule 
{ 
    public int Id { get; set; } 
    public RuleGroup RuleGroup { get; set; } 
} 


public class RuleGroup 
{ 
    public int Id { get; set; } 
    public List<Rule> RuleList { get; set; } 
} 

一個RuleGroup有一系列規則。我AutoMapper設置如下:

Mapper.CreateMap<RuleRecord, FirstSolar.Mes.Core.Entities.Recipe.Rule>() 
    .ForMember(destination => destination.RuleGroup, source => source.Ignore()) 
    .ForMember(destination => destination.Id, source => source.MapFrom(item => item.RuleId)); 
Mapper.CreateMap<IList<RuleRecord>, IList<FirstSolar.Mes.Core.Entities.Recipe.Rule>>(); 

Mapper.CreateMap<RuleGroupRecord, FirstSolar.Mes.Core.Entities.Recipe.RuleGroup>() 
    .ForMember(destination => destination.Id, source => source.MapFrom(item => item.RuleGroupId)); 
Mapper.CreateMap<IList<RuleGroupRecord>, IList<FirstSolar.Mes.Core.Entities.Recipe.RuleGroup>>(); 

當我試圖映射一個RuleGroupRecord(LinqToSQL對象)RuleGroup(DTO),AutoMapper說,我需要添加一個映射RuleGroup.RuleList。我想知道爲什麼,因爲我定義瞭如何映射一個RuleRecord和一個List。

如果必須,我該怎麼做?

回答

2

只需添加(我希望我的語法正確的,但你應該明白我在暗示什麼):

.ForMember(destination => destination.RuleList, source => source.MapFrom(item => item.Rules)); 

到第二映射。當您在第一個映射中處理RuleRecordRule的通用映射時,您並未告訴automapper映射特定屬性RuleGroup.RuleList

+0

這會將另一個錯誤替換爲另一個錯誤。我認爲這個問題的原因是,在你的例子中,source(item.Rules)與目標(destination.RuleList)不是同一個類型。源是實體(L2S)的實體集,目標是我自己的DTO列表。我從AutoMapper返回的異常只是一個通用映射例外。沒有詳細說明實際問題是什麼。 – 2011-03-12 22:02:26

+0

嘗試刪除特定的'IList'映射。無論如何,你並不需要這些,我認爲他們實際上正在破壞測繪。 – Femaref 2011-03-12 22:07:17