I have a simple expression that I use to convert domain objects into DTOs.
public static Expression<Func<Person, PersonDetailsShallow>> ToPersonDetailsShallow
=> (person) => new PersonDetailsShallow()
{
PersonId = person.Id,
Tag = person.Tag
};
public class Person
{
public string Id { get; internal set; }
public string Tag { get; internal set; }
}
public class PersonDetailsShallow
{
public string PersonId { get; internal set; }
public string Tag { get; internal set; }
}
I am now dreaming of a way to embed this Expression
into another expression, something like
// define one more entity and dto to have something to work with
public class Purchase
{
public double Price { get; internal set; }
public Person Purchaser { get; internal set; }
}
public class PurchaseDetailsShallow
{
public double Price { get; internal set; }
public PersonDetailsShallow Purchaser { get; internal set; }
}
public static Expression<Func<Purchase, PurchaseDetailsShallow>> ToPurchaseDetailsShallow
=> (purchase) => new PurchaseDetailsShallow()
{
Price = purchase.Price,
Purchaser = ExpandExpression(ToPersonDetailsShallow, purchase.Purchaser)
}
where ExpandExpression
works some magic such that the resulting ToPurchaseDetailsShallow
looks like this
(purchase) => new PurchaseDetailsShallow()
{
Price = purchase.Price,
Purchaser = new PersonDetailsShallow()
{
PersonId = purchase.Purchaser.Id,
Tag = purchase.Purchaser.Tag
}
}
It appears that there are libraries that can achieve this as shown in this question
Can I reuse code for selecting a custom DTO object for a child property with EF Core?
but I am hoping for a simpler way that does not involve adding new dependencies.
I am aware that I could fake it using Compile()
a la
public static Expression<Func<Purchase, PurchaseDetailsShallow>> ToPurchaseDetailsShallow
=> (purchase) => new PurchaseDetailsShallow()
{
Price = purchase.Price,
Purchaser = ToPersonDetailsShallow.Compile()(purchase.Purchaser)
}
which however does not create the right expression tree, but only shows similar behavior when evaluating the expression.