entity-frameworkef-code-firstlazy-loadingautomapper

Automapper lazy loading. Entity framework


I have an Entity and a ViewModel

public class Order
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [ForeignKey("DeliveryMethod")]
    public int DeliveryMethodId { get; set; }
    public virtual RouteDeliveryMethod DeliveryMethod { get; set; }
}

and

public class OrderViewModel
{
    public string Name { get; set; }
    public int? DeliveryMethodId { get; set; }
}

My controller receives the view model and uses automapper to map it back to the entity

[HttpPost]
public ActionResult GetQuote(OrderViewModel ordervm)
{
    Order order = Mapper.Map<Order>(ordervm);
    // Do something with the order...

    return View();
}

This is all fine, however after it has done the mapping back to an Order object it doesn't load the DeliveryMethod, DeliveryMethodId has a valid value, but DeliveryMethod is always null.

Shouldn't the DeliveryMethod load due to the lazy loading?


Solution

  • Automapper looks only at mapped properties. If you have not mapped destination property DeliveryMethod to any of source properties, then it will not be hit during mapping. If property getter is not executed, then entity is not lazy-loaded.

    But even if this property was hit, it would not be lazy-loaded anyway. Because Automapper will create new instance of Order class during mapping. But for lazy-loading you need instance of order proxy class which have your DbContext inside. This proxy does loading of related entities when you try to read their values. With plain Order class instance lazy-loading cannot work.