c# - 使用 AutoMapper 从 ICollection<EFEntity> 映射到 ICollection<ViewModel> 到 ICollection<Object>

标签 c# automapper

配置 AutoMapper 以映射的最佳/最简单方法是什么 ICollection<DomainModel>ICollection<ViewModel>ICollection<object>

我有一个如下所示的 DomainModel:

public class DomainModel
{
    ICollection<EFEntity> Data;

    //other stuff
}

我想将此 DomainModel 映射到 MVC ViewModel:

public class ViewModelWithCollection
{
    ICollection<object> Data;

    //other stuff
}

我需要 ICollection<object>因为我使用以下 View :

@model ViewModelWithCollection
<table>
    @foreach(object x in Model.Data)
    {
        Html.Partial("PartialView", x)
    }
</table>

对于每个具体的 ViewModel,都存在一个像这样的 PartialView:

@model ViewModel
<tr> <!-- Render specific View Data --> <tr>

当我使用

AutoMapper.Map<DomainModel, ViewModelWithCollection>(source, target);

AutoMapper 只是做了这样的事情:

object target = (object)EFEntity

这当然行不通。

最佳答案

经过几个小时的搜索,我发现我想要实现的东西叫做映射继承:https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance

所以我的问题的解决方案是

AutoMapper.Map<DomainModel, ViewModelWithCollection>();

AutoMapper.Map<EFEntity, object>()
    .Include<EFEntity, ViewModel>();

AutoMapper.Map<EFEntity, ViewModel>();

关于c# - 使用 AutoMapper 从 ICollection<EFEntity> 映射到 ICollection<ViewModel> 到 ICollection<Object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590980/

相关文章:

c# - 不能发送单键功能到远程桌面

c# - Fisher-Yates 在单个字符串上洗牌与使用等长排列?

.net - 自动映射器 : mapping issue with inheritance and abstract base class on collections with Entity Framework 4 Proxy Pocos

c# - AutoMapper 可以为接口(interface)创建映射,然后使用派生类型进行映射吗?

c# - 如何在运行时仅在类上添加属性?

c# - 无法使用 XML 使用 Rest Sharp PUT/POST

automapper - 在 ASP.NET Core 中配置 AutoMapper

c# - AutoMapper:如何获取目标属性的名称

c# - 如何通知子控件父控件发生变化

c# - 使用自动映射器将一个源类映射到多个派生类