Dynamic linq for object collection - Target object is not an ExpandoObject

.net-core .net-core-2.1 c# dynamic-linq reflection

Question

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() ?? "";
}
1
1
1/12/2019 7:19:32 PM

Popular Answer

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)");
1
1/12/2019 1:45:26 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow