簡體   English   中英

無法將服務層實體映射到域模型實體

[英]Unable to map a service layer entity to domain model entity

我正在嘗試使用一個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; }
}

可以在生成的reference.cs找到的BusinessService實體具有與DomainModel實體同名的屬性。

我在這兩種情況下都做錯了什么?

您的報告客戶返回業務實體列表 ,並且您試圖將它們映射到單個實體。 我認為您應該將業務實體的集合映射到視圖模型的集合(當前,您正在嘗試將集合映射到單個視圖模型):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM