Automapper只返回Matched属性值

本文关键字:属性 Matched 返回 Automapper | 更新日期: 2023-09-27 18:25:46

这里我使用automapper类将"userdetails"类与"FinalizedDetails"类进行匹配。我试过了,但我只得到了姓氏值,但对于NameFirst和BooksInfo,它什么都不返回。如何解决这个问题我对automapper很陌生。我不了解Automapper类的全部用法。

家庭控制器:

 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.chtml:

@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 : 

Automapper只返回Matched属性值

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