【问题标题】:AutoMapper between Model and ViewModel with multiple properties具有多个属性的模型和视图模型之间的 AutoMapper
【发布时间】:2013-09-27 15:14:01
【问题描述】:

试图在视图模型和我的模型之间进行映射。在这种情况下,我从 Web 服务获取数据(创建强类型视图),然后将其加载到表单中。然后我验证来自 Web 服务的客户端数据,提交表单。它将根据我的数据库中是否有记录进行插入或更新。

我一直想使用 AutoMapper,所以这是我第一次使用它。我希望将 SearchResult 中的属性映射到我的客户端模型。

namespace Portal.ViewModels
{
public class ClientSearch
{
    public SearchForm searchForm { get; set; }
    public SearchResult searchResult { get; set; }
}

public class SearchForm
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DOB { get; set; }
    public string AccNumber { get; set; }
}

public class SearchResult
{
    public int ClientID { get; set; }
    public string AccNumber { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Phone { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Gender { get; set; }
    public string DOB { get; set; }
    public int Age { get; set; }
}
}

namespace Portal.Models
{
public class Client
{
    public int ClientID { get; set; }
    public string AccNumber { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Phone { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Gender { get; set; }

    [Display(Name = "Date of Birth")]
    public DateTime DOB { get; set; }
    public int Age { get; set; }

}
}

在下面的控制器中,我正在尝试使用 AutoMapper 将 clientSearch 中的数据映射到基于 HttpPost 的客户端模型。

但是,我收到错误消息:尝试创建 Map 时,只能将赋值、调用、递增、递减、等待和新对象表达式用作语句。这是我使用 AutoMapper 的尝试。

[HttpPost]
public ActionResult Process(ClientSearch clientSearch)
{
    // Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
    Mapper.CreateMap<ClientSearch, Client>;

    Client client = Mapper.Map<ClientSearch, Client>(clientSearch);
    ClientRepository.InsertOrUpdate(client);
    ClientRepository.Save();

}

【问题讨论】:

  • 以防万一您没有注意到,您的编译器会告诉您这一点。基本上,Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement 它告诉你你写的不是一个声明。这实际上非常准确;)

标签: c# asp.net asp.net-mvc asp.net-mvc-4 automapper


【解决方案1】:

你似乎错过了你的“()”:

 Mapper.CreateMap<ClientSearch, Client>;

即应该是:

Mapper.CreateMap<ClientSearch, Client>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 2017-06-23
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多