I try to dynamically read the property values based on the text naming of these properties. This simply works for nested classes. But if there is a nested collection class, I would like to be able to select an item using a dynamic linq. Unfortunately, while reading in the collection, it returns
'Target object is not an ExpandoObject' (.FirstOrDefault).
Any idea to edit or possibly another solution?
My Code (.net core 2.1):
string value = string.Empty;
var dataClassProperty = dataClass.GetType().GetProperty(dataClassPropertyName).GetValue(dataClass, null);
if (dataClassProperty is IEnumerable<object>)
{
object nestedPropertyItem = (dataClassProperty as IEnumerable<object>)
.AsQueryable()
.FirstOrDefault(collectionDynamicLinq);
if (nestedPropertyItem != null)
value = nestedPropertyItem.GetType().GetProperty(nestedPropertyName).GetValue(nestedPropertyItem, null)?.ToString() ?? "";
}
If you want to use Dynamic Linq on (database) entity classes, you could use System.Linq.Dynamic.Core.
With this you can easily write text based linq, like
var query = db.Customers
.Where("City == @0 and Orders.Count >= @1", "London", 10)
.OrderBy("CompanyName")
.Select("new(CompanyName as Name, Phone)");