我对自动映射很陌生,甚至对 ValueInjecter 也很陌生。如果这是一个简单的问题,我很抱歉,但我似乎无法在任何地方找到答案。
我将如何进行递归映射?例如,这是我当前的工厂方法,将 Subject(来自我的数据服务)映射到 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”类型。