AutoMapper Mapping fields to Class
I'm trying to accomplish the following. I have a DTO that returns values from the database and I'd like to map the DTO to a Model. My model has a property that has a class type. I'd like to set that property to a new instance of the class using the values in the DTO. So here is some code that shows what I'm trying to do.
public class ItemDTO {
public int ItemID { get; set; }
public int ItemPartID { get; set; }
public string ItemPartName { get; set; }
}
public class ItemModel {
public int ItemID { get; set; }
public ItemPartModel ItemPart { get; set; }
}
public class ItemPartModel {
public int ItemPartID { get; set;开发者_Go百科 }
public string ItemPartName { get; set; }
}
public void DoMapping() {
Mapper.CreateMap<ItemDTO, ItemModel>()
.ForMember(m => m.ItemPart,
dto => dto.MapFrom(ipm => new ItemPartModel() {
ItemPartID = ipm.ItemPartID,
ItemPartName = ipm.ItemPartName}));
}
When I use the map created here, I end up with the ItemModel's ItemPart property having values of 0 and ItemPartName of 'ItemPartName'
Please let me know if there is anymore info I can provide and thanks for viewing.
It seems that my logic was fine and that the syntax is correct. It was a simple mistake in my code where I was calling the ItemPart property. Originally, my model contained the ID (int) and Name property (string) of the item part (naming is different in my project than in my example). I replaced those two properties to a single property using the Class Type ItemPartModel, which encapsulated both fields. My UI code wasn't updated and was simply displaying the Class Item part .ToString(). Once I updated my UI code, it worked. Anyway, that's my excuse, however I will leave this question as is since I did have some trouble finding a solution to what I was trying to do here with the Automapper and someone else may find this helpful.
精彩评论