使用 Automapper 展平属性的子类
给定类:
public class Person
{
public string Name { get; set; }
}
public class Student : Person
{
public int StudentId { get; set; }
}
public class Source
{
public Person Person { get; set; }
}
public class Dest
{
public string PersonName { get; set; }
public int? PersonStudentId { get; set; }
}
我想使用 Automapper 来映射 Source ->目的地。
该测试显然失败了:
Mapper.CreateMap<Source, Dest>();
var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }};
var dest = Mapper.Map<Source, Dest>(source);
Assert.AreEqual(5, dest.PersonStudentId);
鉴于“Person”实际上是整个域模型中广泛使用的数据类型,映射此问题的最佳方法是什么。
编辑:目的是保留“Dest”对象,该对象将具有为“Person”子类型的所有属性定义的字段。因此,我们可以拥有如下所示的源对象,并且不希望为“Person”子类的每种可能的组合创建 Dest 对象:
public class Source2
{
public Person Value1 { get; set; }
public Person Value2 { get; set; }
public Person Value3 { get; set; }
public Person Value4 { get; set; }
public Person Value5 { get; set; }
}
Given the classes:
public class Person
{
public string Name { get; set; }
}
public class Student : Person
{
public int StudentId { get; set; }
}
public class Source
{
public Person Person { get; set; }
}
public class Dest
{
public string PersonName { get; set; }
public int? PersonStudentId { get; set; }
}
I want to use Automapper to map Source -> Dest.
This test obviously fails:
Mapper.CreateMap<Source, Dest>();
var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }};
var dest = Mapper.Map<Source, Dest>(source);
Assert.AreEqual(5, dest.PersonStudentId);
What would be the best approach to mapping this given that "Person" is actually a heavily used data-type throughout our domain model.
Edit: The intent is to persist the "Dest" objects which will have fields defined for all properties of the sub-types of "Person". Hence we could have source objects like the following and would prefer not to have to create Dest objects for every possible combination of "Person" sub-classes:
public class Source2
{
public Person Value1 { get; set; }
public Person Value2 { get; set; }
public Person Value3 { get; set; }
public Person Value4 { get; set; }
public Person Value5 { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,利用吉米的建议,我已经确定了以下解决方案:
很想听到建议/改进。
Well using Jimmy's suggestion I've settled on the following solution:
Would love to hear suggestions/improvements.