我有一个具有子类和属性的原始文档对象。我有一个不同的对象,它是该对象的一个子集,它保存从表单输入的值,如果您愿意,可以是视图模型。由于两个对象都来自同一类,因此结构是相同的。
有没有办法将新对象的值一般分配给原始对象?我目前的方法是明确的:
myOrigDoc.Introduction.Name = myDoc.Introduction.Name;
myOrigDoc.Introduction.Clients[0].Firstname =
myDoc.Introduction.Clients[0].Firstname;
另外我想确保只分配具有值(非空)的属性。
这可以做到吗?
提前谢谢了,
埃德
编辑:对 ValueInjector 及其类进行实验,以防止分配空值。
public class StrNotNull: ConventionInjection
{
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Value != null;
}
//protected override object SetValue(ConventionInfo c)
//{
// return c.SourceProp.Value.ToString();
//}
}
调用它的代码:
myOrigDoc.InjectFrom<StrNotNull>(myDoc);
EDIT2:Automapper 使用的可能代码。虽然还不确定是否忽略空值,因此确实进行了合并。
Mapper.CreateMap<Document, Document>();
myOrigDoc = Mapper.Map<Document, Document>(myDoc);
提前感谢您的任何建议和帮助。