I have the following viewmodels (example for simplicity).
public class ProductVM {
public int ID { get; set; }
public string Name { get; set; }
}
public class OrderVM {
public ProductVM Product { get; set; }
public double Price { get; set; }
public DateTime OrderDate { get; set; }
}
I'm using nested viewmodel to avoid repeating myself (my real code is much more complex), so I'd like to avoid needing to flatten the Product all the time.
I'm using DevExpress XPO as an ORM, which supports selecting nested viewmodels well. However I have a problem with the Select expression generated by Project().To<OrderVM>()
.
When I (manually) write the following query, everything works like a charm. Filtering, sorting, grouping AFTER the projection works as expedted (used by a gridview for example).
var q = myUnitOfWork.Query<Order>().Select(e =>
new OrderVM() {
OrderDate = e.OrderDate,
Price = e.Price,
Product = new ProductVM() {
ID = e.Product.ID,
Name = e.Product.Name,
}
});
One side-effect it has is that if - let's say - an Order has no Product, then the Product in the viewmodel will not be null, but will have everything empty (ID = 0, Name = null, etc). But this is fine for me, because the result is being displayed in a grid, where I can comfortable handle this.
So now when I use the Project.To<OrderVM>()
, the Select expression generated by AutoMapper will look like this:
var q = myUnitOfWork.Query<Order>().Select(e =>
new OrderVM() {
OrderDate = e.OrderDate,
Price = e.Price,
Product = e.Product != null ? new ProductVM() {
ID = e.Product.ID,
Name = e.Product.Name,
} : null
});
This is of course a semantically more correct approach, however, XPO will crash on filtering, sorting, etc. So I somehow need to avoid this IIF
expression and stay with the pure nested initializer. Is it somehow possible, or is there any workaround? Unfortunately I'm not so experienced in playing with expression trees.