我对自动映射很新,甚至比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'。
答案 0 :(得分:2)
您收到此错误的原因是因为您将源属性Children与目标对象中的所有属性进行匹配,因此将为所有匹配调用SetValue。
你需要的是:
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name
&& c.SourceProp.Name == "Children";
}