How do I manually populate ViewModel (Not using AutoMapper!)

前端 未结 2 468
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 23:14

I know there are a lot of posts on the subject but I cannot find one that helps me do what I want. I know that I will eventually be using Automapper but before I start playing w

相关标签:
2条回答
  • 2021-02-14 23:38

    In order to populate a list of shipments based on your view model object you would need to create a mapping method to map from your collection of shipments from your database to a collection of shipments based on your view model:

    var model = new List<ShippingHeaderSummaryVM>();
    
    foreach(var h in shipments)
    {
    
        var viewModel = new ShippingHeaderSummaryVM
        {
        ID = h.ID
        Site = r.Site
        DateShipped = h.DateShipped
        EstDeliveryDate = h.EstDeliveryDate
        TrackingNo = h.TrackingNumber
        FromSitePOC = e.LastName
        NumOrders = h.ShippingLI.Count
        Shipper = s.Shipper
        HeaderComments = h.HeaderComments
        }
    
        model.Add(viewModel);
    }
    
    return model;
    

    As a side note, this becomes a one liner after you have AutoMapper up and running:

    var model = Mapper.Map<IEnumerable<ShippingHdr>, IEnumerable<ShippingHeaderSummaryVM>>(shipments);
    

    While, learning how to do things manually is great. Manually mapping models doesn't really benefit you in any way or form. Go with AutoMapper.

    0 讨论(0)
  • 2021-02-15 00:03

    You can also use Linq to do something like this...

    shipments.Select(h => new ShippingHeaderSummaryVM(){
        ID = h.ID,
        Site = r.Site,
        DateShipped = h.DateShipped,
        EstDeliveryDate = h.EstDeliveryDate,
        TrackingNo = h.TrackingNumber,
        FromSitePOC = e.LastName,
        NumOrders = h.ShippingLI.Count,
        Shipper = s.Shipper,
        HeaderComments = h.HeaderComments
    });
    

    Note that while mapping view models is great for passing to a view, always do it manually when reading from a view model to update your database.

    Edit: Thanks for the typo correction:-)

    0 讨论(0)
提交回复
热议问题