I'm pretty new to auto-mapping, and even newer to ValueInjecter. I'm sorry if this is an easy question, but I can't seem to find the answer anywhere.
How would I do a recursive mapping? For example, here is my current factory method that maps a Subject (from my data service) to a 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;
}
I'm guessing this is a bread-and-butter type of situation for ValueInjecter, so if someone could just point me in the right direction I'd appreciate it!
Here's a fake, but complete code sample:
[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);
开发者_StackOverflow中文版 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;
}
}
EDIT - I know this is a naive approach, that's not recursive. Right now I'm just trying to get this far without the exception
Right now I get:
System.ArgumentException: Object of type 'System.Collections.Generic.List`1[TestValueInjector.SubjectViewModel]' cannot be converted to type 'System.String'.
the reason you were getting this error is because you were matching the source property Children with all the properties from the target object, so SetValue is called for all the matches.
What you needed was this:
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name
&& c.SourceProp.Name == "Children";
}
精彩评论