2013-10-17 69 views
0

我想使用一个GetData获取一些数据。该商业方法从控制器通过这个行动方法的服务层叫做:无法将服务层实体映射到域模型实体

public PartialViewResult Grid() 
{ 
    var model = new DomainModels.Reports.MeanData(); 
    using (var reportsClient = new ReportsClient()) 
    { 
     model = reportsClient.GetData(reportType, toDate, fromDate); //<= error on this line 
    } 
    return PartialView("_Grid", model); 
} 

我得到这个错误:

Cannot implicitly convert type ' System.Collections.Generic.List<BusinessService.Report.MeanData> ' to ' DomainModels.Reports.MeanData '

一位同事曾使用Automapper这个建议,所以我改变了行动方法是这样的基础上,他什么工作:

public PartialViewResult Grid() 
{ 
    using (var reportsClient = new ReportsClient()) 
    { 
     Mapper.CreateMap<DomainModels.Reports.MeanData, BusinessService.Report.MeanData>(); 
     var model = reportsClient.GetData(reportType, toDate, fromDate); 
     DomainModels.Reports.MeanData viewModel = //<= error on this line 
      Mapper.Map<DomainModels.Reports.MeanData, BusinessService.Report.MeanData>(model); 
    } 
    return PartialView("_Grid", viewModel); 
} 

我得到这个错误:

The best overloaded method match for ' AutoMapper.Mapper.Map<DomainModels.Reports.MeanData,BusinessService.Report.MeanData> (DomainModels.Reports.MeanData)' has some invalid arguments

的的DomainModel实体:

用相同的名称的DomainModel实体
[DataContract] 
public class MeanData 
{ 
    [DataMember] 
    public string Description { get; set; } 
    [DataMember] 
    public string Month3Value { get; set; } 
    [DataMember] 
    public string Month2Value { get; set; } 
    [DataMember] 
    public string Month1Value { get; set; } 
} 

设置businessService实体,其可以在所生成的reference.cs发现由具有属性。

我在这两种情况下做错了什么?

+0

@lazyberezovsky:我想你的答案,并得到了错误:'无法隐式转换类型“System.Collections.Generic.List ”到“系统.Collections.Generic.List '' – Animesh

回答

1

您的报告客户返回列表的商业实体,你试图将它们映射到单个实体。我想你应该业务实体的集合视图模型(目前你正试图集合映射到单一视图模型)的集合映射:

using (var reportsClient = new ReportsClient()) 
{ 
    List<BusinessService.Report.MeanData> model = 
     reportsClient.GetData(reportType, toDate, fromDate); 
    IEnumerable<DomainModels.Reports.MeanData> viewModel = 
     Mapper.Map<IEnumerable<DomainModels.Reports.MeanData>>(model); 
} 

return PartialView("_Grid", viewModel); 

移动创建映射到应用程序启动:

Mapper.CreateMap<DomainModels.Reports.MeanData, BusinessService.Report.MeanData>(); 

也可以考虑,如果你有类型具有相同名称的使用别名:

using BusinessMeanData = BusinessService.Reports.MeanData; 
using MeanDataViewModel = DomainModel.Reports.MeanData; 

或者(更好)将ViewModel后缀添加到作为视图模型的类型的名称。在这种情况下,代码如下:

using (var reportsClient = new ReportsClient()) 
{ 
    var model = reportsClient.GetData(reportType, toDate, fromDate); 
    var viewModel = Mapper.Map<IEnumerable<MeanDataViewModel>>(model); 
} 

return PartialView("_Grid", viewModel); 
+0

@Animesh对不起,没有注意到你有两个同名的实体。现在它应该工作。使用AutoMapper映射集合时,不要忘记指定IEnumerable目标类型 –

+0

对不起,这不起作用。我花了最后几天试图利用这种映射,但它没有奏效。我知道这段代码没有错,但我最终使用服务层类型作为View的模型(截止时间定向开发让我这么做,对不起)。无论如何感谢您的洞察力。 – Animesh