Select Anonymous Type Using Dynamic Expressions API

I am using the Dynamic Expression API ( System.Linq.Dynamic) with LINQ to Entities. My LINQ request is below.

var query = this.db.Products.AsQueryable()
           .Where(strCondition)
           .OrderBy("ProductNumber")
           .Select("new(ProductNumber, ProductDescription, ProductCategory.Name)");

Now that I have a query, I don’t know how to get the value of each of the fields.

string strTemp;
foreach (var item in query)
{
    strTemp = item.?
}

This is an anonymous type, so I cannot use strongly the type to get the value. What can I do? The reason I choose to receive anonymous type fields is because I need to get the ProductCategory.Name field as a result. Is there a better way to get ProductCategory.Name as a result using the Dynamic Expression API? Can anyone help?

+2
source share
2 answers

- dynamic, - ( object, DynamicClass).

foreach (dynamic item in query)
{
    string ProductNumber      = item.ProductNumber;
    string ProductDescription = item.ProductDescription;
    string Name               = item.Name;
}

.

// static (extension) method to read the property
public static T GetProperty<T>(this DynamicClass self, string propertyName)
{
    var type = self.GetType();
    var propInfo = type.GetProperty(propertyName);
    return (T)propInfo.GetValue(self, null);        
}

// usage:
foreach (DynamicClass item in query)
{
    // using as an extension method
    string ProductNumber      = item.GetProperty<string>("ProductNumber");
    // or as a static method
    string ProductDescription = GetProperty<string>(item, "ProductDescription");
    string Name               = item.GetProperty<string>("Name");
}
+1

, . VS intellisense .

string strTemp;
        foreach (var item in query)
        {
            strTemp = item.ProductItem;
        }

:

.Select("new(ProductNumber as Number, ProductDescription as Description, ProductCategory.Name as Name)")
0

Source: https://habr.com/ru/post/1790132/


All Articles