2
我很新的自動映射,甚至更新的ValueInjecter。如果這是一個簡單的問題,我很抱歉,但我似乎無法在任何地方找到答案。ValueInjecter - 遞歸映射
我該如何做一個遞歸映射?例如,下面是一個映射主題(從我的數據服務)我目前的工廠方法到SubjectViewModel:
private SubjectViewModel createSubject(DataService.SubjectResult s) {
SubjectViewModel result = new SubjectViewModel();
result.SubjectName = s.SubjectName;
result.id = s.id;
foreach (DataService.SubjectResult sChild in s.Children)
result.ChildSubjects.Add(createSubject(sChild));
return result;
}
我猜這是形勢的麪包和奶油類型ValueInjecter,所以如果有人能指出我正確的方向,我會很感激!
這裏有一個假的,但完整的代碼示例:
[TestClass]
public class UnitTest1 {
[TestMethod]
public void TestMethod1() {
Subject S = new Subject() {
id = 1,
SubjectName = "S1", Children = { new Subject() { id = 2, SubjectName = "S1a" },
new Subject() { id = 3, SubjectName = "S1b" }}
};
SubjectViewModel VM = new SubjectViewModel();
VM.InjectFrom<CollectionToCollection>(S);
Assert.AreEqual(2, VM.Children.Count);
}
}
public class Subject {
public Subject() {
Children = new List<Subject>();
}
public string SubjectName { get; set; }
public int id { get; set; }
public List<Subject> Children { get; private set; }
}
public class SubjectViewModel {
public SubjectViewModel() {
Children = new List<SubjectViewModel>();
}
public string SubjectName { get; set; }
public int id { get; set; }
public List<SubjectViewModel> Children { get; set; }
}
public class CollectionToCollection : Omu.ValueInjecter.ConventionInjection {
protected override bool Match(ConventionInfo c) {
return c.SourceProp.Name == "Children";
}
protected override object SetValue(ConventionInfo c) {
List<SubjectViewModel> result = new List<SubjectViewModel>();
foreach (Subject S in (c.SourceProp.Value as IEnumerable<Subject>))
result.Add(new SubjectViewModel());
return result;
}
}
編輯 - 我知道這是一個幼稚的做法,這不是遞歸。現在,我只是試圖讓這個至今沒有例外
現在我得到:
System.ArgumentException:對象 型 「System.Collections.Generic.List`1 [TestValueInjector的.SubjectViewModel]' 無法轉換爲類型 'System.String'。
太好了,謝謝! – 2011-04-06 13:52:11