如何使用 AutoMapper 将多个子类映射到一个类中?
假设我有三个类,它们是基类的子类:
public class BaseClass
{
public string BaseName { get; set; }
}
public class Subclass1 : BaseClass
{
public string SubName1 { get; set; }
}
public class Subclass2 : BaseClass
{
public string SubName2 { get; set; }
}
public class Subclass3 : BaseClass
{
public string SubName3 { get; set; }
}
我想将它们映射到如下所示的 ViewModel 类:
public class ViewModel
{
public string BaseName { get; set; }
public string SubName1 { get; set; }
public string SubName2 { get; set; }
public string SubName3 { get; set; }
}
ViewModel
只是组合所有子类的属性并将其展平。我尝试像这样配置映射:
AutoMapper.CreateMap<BaseClass, ViewModel>();
然后我尝试像这样从数据库中获取数据:
var items = Repo.GetAll<BaseClass>();
AutoMapper.Map(items, new List<ViewModel>());
但是,最终发生的情况是只有 BaseName
属性将填充在 ViewModel.我将如何配置 AutoMapper 以便它也映射子类中的属性?
Let's assume I have three classes that are subclasses of a base class:
public class BaseClass
{
public string BaseName { get; set; }
}
public class Subclass1 : BaseClass
{
public string SubName1 { get; set; }
}
public class Subclass2 : BaseClass
{
public string SubName2 { get; set; }
}
public class Subclass3 : BaseClass
{
public string SubName3 { get; set; }
}
I would like to map these to a ViewModel class that looks like this:
public class ViewModel
{
public string BaseName { get; set; }
public string SubName1 { get; set; }
public string SubName2 { get; set; }
public string SubName3 { get; set; }
}
ViewModel
simply combines the properties on all of the subclasses and flattens it. I tried to configure the mapping like so:
AutoMapper.CreateMap<BaseClass, ViewModel>();
Then I tried grabbing data from my database like so:
var items = Repo.GetAll<BaseClass>();
AutoMapper.Map(items, new List<ViewModel>());
However, what ends up happening is that only the BaseName
property will be populated in the ViewModel
. How would I configure AutoMapper so that it will map the properties in the subclasses as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AutoMapper 中似乎存在错误或限制,您需要相应的 TSource 和 TDestination 层次结构。给定:
您需要以下视图模型:
然后以下代码可以工作:
There appears to be a bug or limitation in AutoMapper that you need corresponding TSource and TDestination hierarchies. Given:
You need the following view models:
The following code then works:
试试这个:
Try this: