简体   繁体   中英

Mapping joined Domain Model to View Model using Automapper

In my business logic class I am joining two data models and returning back to the controller as IEnumerable. I need to map these collection to the List using automapper .But it is not working as expected.

Logic class

 public IEnumerable<object> GetPurchaseOrderDetailsByPersonId(long personId)
    {
        var purchaseOrderDetails = from pom in _unitOfWork.DbSet<PurchaseOrderMain>()
                                   join rep in _unitOfWork.DbSet<RepresentativeMaster>() on pom.REPM_ID equals rep.REPM_ID
                                   where pom.REPM_ID == personId
                                   select new { pom.RM_ID,pom.OrderNo,pom.OrderAmount,pom.OrderDate ,rep.RepName };

        return purchaseOrderDetails;
    }

Controller

public ActionResult Index()
    {
        List<object> purchaseOrder = _CLS_PurchaseOrder_BLL.GetPurchaseOrderDetailsByPersonId(PersonId).ToList();

        return View(purchaseOrder.ToEntity<OMOS.Models.PurchaseOrderDetails>());
    }

ToEntity() in extension class

  public static List<TDestination> ToEntity<TDestination>(this List<object> OBJSource)
    {
        AutoMapper.Mapper.CreateMap<object, TDestination>();
        List<TDestination> destination = new List<TDestination>();//Handling the null destination
        foreach (object source in OBJSource)
        {
            destination.Add(AutoMapper.Mapper.Map<object, TDestination>(source));
        }
        return destination;
    }

But resulted mapping is not as expected.

Change your code like this.

public static List<TDestination> ToEntity<TDestination>(this List<object> OBJSource)
    {
        List<TDestination> destination = new List<TDestination>();//Handling the null destination

        foreach (object source in OBJSource)
            destination.Add(AutoMapper.Mapper.DynamicMap<TDestination>(source));

        return destination;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM