0

我正在尝试使用一个来获取一些数据GetData。这个业务方法是通过这个 Action 方法中的一个服务层从控制器调用的:

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);
}

我收到此错误:

无法将类型“ System.Collections.Generic.List<BusinessService.Report.MeanData>”隐式转换为“ DomainModels.Reports.MeanData

一位同事建议为此使用 Automapper,所以我根据对他有用的方法更改了这样的 Action 方法:

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);
}

我收到此错误:

AutoMapper.Mapper.Map<DomainModels.Reports.MeanData,BusinessService.Report.MeanData>' (DomainModels.Reports.MeanData)'的最佳重载方法匹配有一些无效参数

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与 DomainModel 实体同名的属性。

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

4

1 回答 1

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);
于 2013-10-17T14:37:58.617 回答