Automapper仅返回Matched属性值

时间:2013-07-31 04:55:11

标签: c# asp.net-mvc automapper

这里我使用的是automapper类,将“userdetails”类与“FinalizedDetails”类相匹配。我试过但我只得到姓氏值但是对于NameFirst和BooksInfo它什么也没有返回。如何解决这个问题我对automapper很奇怪。 我不明白Automapper类的完整用法。

HomeController中:

 public ActionResult Index()
 {
     UserDetails objDao = setData();
     Mapper.CreateMap<UserDetails, FinalizedDetails>();
     FinalizedDetails objDetails =  Mapper.Map<UserDetails,FinalizedDetails >(objDao);
     return View(objDetails);
 }

 [HttpPost]
 public ActionResult Index(string id)
 {
     return View();
 }
 private UserDetails setData()
 {
     UserDetails daoObj = new UserDetails();
     daoObj.FirstName = "Mike";
     daoObj.LastName = "Castillo";
     daoObj.Salary = 6000;
     daoObj.Certified = true;
     daoObj.BookDetails = new Books();
     daoObj.BookDetails.BookName = "Auto Mapper Tuts";
     daoObj.BookDetails.BookPrice = 200;
     daoObj.BookDetails.BookDescription = "A brief Description about Automapper class";
     return daoObj;
 }

Index.cshtml:

@model AutoMapper_Demo.Models.FinalizedDetails
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
    @Html.TextBox("First anme");
    <p>First name : @Model.FirstName</p>
    <p>Last Name : @Model.LastName</p>
    <p>BookInfo : @Model.BooksInfo</p>

模特:

public class UserDetails
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string getFullName()
    {
        return FirstName + " " + LastName;
    }
    public int Salary { get; set; }
    public bool Certified { get; set; }
    public Books BookDetails { get; set; }
}
public class Books
{
    public string BookName { get; set; }
    public int BookPrice { get; set; }
    public string BookDescription { get; set; }
}
public class FinalizedDetails
{
    public string NameFirst { get; set; }
    public string LastName { get; set; }
    public string BooksInfo { get; set; }
}

输出

First name : 

Last Name : Castillo

BookInfo : 

1 个答案:

答案 0 :(得分:1)

Automapper不会自动映射没有匹配名称的属性(实际上它无法知道如何),但您可以自己指定:

Mapper.CreateMap<UserDetails, FinalizedDetails>()
      .ForMember(d => d.NameFirst, o => o.MapFrom(s => s.FirstName));

修改

由于您已经询问了如何映射BookInfo,并且假设您想要某种摘要,您可以(例如)执行以下操作:

Mapper.CreateMap<UserDetails, FinalizedDetails>()
      .ForMember(d => d.NameFirst, o => o.MapFrom(s => s.FirstName))
      .ForMember(d => d.BooksInfo,
                 o =>
                 o.MapFrom(
                     s => string.Format("{0} - ({1})", s.BookDetails.BookName, s.BookDetails.BookDescription)));