【问题标题】:Map from ICollection<EFEntity> to ICollection<ViewModel> to ICollection<Object> with AutoMapper使用 AutoMapper 从 ICollection<EFEntity> 映射到 ICollection<ViewModel> 到 ICollection<Object>
【发布时间】:2012-03-06 20:03:14
【问题描述】:

配置 AutoMapper 以将 ICollection&lt;DomainModel&gt; 映射到 ICollection&lt;ViewModel&gt;ICollection&lt;object&gt; 的最佳/最简单方法是什么?

我有一个如下所示的 DomainModel:

public class DomainModel
{
    ICollection<EFEntity> Data;

    //other stuff
}

我想将此 DomainModel 映射到 MVC ViewModel:

public class ViewModelWithCollection
{
    ICollection<object> Data;

    //other stuff
}

我需要ICollection&lt;object&gt;,因为我使用以下视图:

@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

这当然行不通。

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。

      我有我的领域模型:

      public class Client
      {
       public int ClientId { get; set; }
       public virtual ICollection<Contract> Contracts { get; set; }
      }
      

      还有我的视图模型:

      public class ClientProfileViewModel
      {
       public int ClientId { get; set; }
       public IEnumerable<ContractProfileViewModel> Contracts { get; set; }
      }
      

      然后在我的映射中:

      Mapper.CreateMap<Client, ClientProfileViewModel>()
            .ForMember(c => c.Contracts, options => options.MapFrom(c => c.Contracts));
      
      Mapper.CreateMap<ClientProfileViewModel, Client>()
            .ForMember(c => c.Contracts, options => options.MapFrom(c => c.Contracts))
      

      【讨论】:

      • 您的示例代码中Client 域模型的ICollection&lt;Contract&gt; 属性是否缺少其名称(可能是Contracts?)?
      • 好地方,我现在已经修好了。这不是问题的一部分,只是我在写上述内容时的一个错字。
      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多