c# - Automapper returns only Matched property values -


here using automapper class match "userdetails" class "finalizeddetails" class. have tried getting last name value namefirst , booksinfo returns nothing. how fix issue strange automapper. didn't understand complete usage of automapper class.

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

models :

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

output

first name :   last name : castillo  bookinfo :  

automapper won't map properties don't have matching names automatically (in fact has no way of knowing how this), can specify yourself:

mapper.createmap<userdetails, finalizeddetails>()       .formember(d => d.namefirst, o => o.mapfrom(s => s.firstname)); 

edit

since you've asked how you'd map bookinfo, , presuming want sort of summary can (for example) following:

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

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -