Select Anonymous type with Dynamic Expression API

只谈情不闲聊 提交于 2019-12-30 10:59:14

问题


I'm using Dynamic Expression API (System.Linq.Dynamic) with LINQ to Entities. My LINQ query is below.

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

Now that I have the "query", I don't know how to get the value of each of the field.

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

It's anonymous type so I can't really use strongly type to get the value. What can I do? The reason I select to get anonymous type fields is because I need to get ProductCategory.Name field into the result. Is there a better way to get ProductCategory.Name in the result with Dynamic Expression API? Can anyone help?


回答1:


The easiest way to deal with it is to declare your loop variable to be dynamic since you don't have any static type information (the inferred static type is object but it is an instance of a DynamicClass).

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

Otherwise you can use reflection manually.

// 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");
}



回答2:


Just use the property name you've used to create your anonymous object. VS intellisense should pick them up.

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

You can specify your own property names as well:

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


来源:https://stackoverflow.com/questions/4050458/select-anonymous-type-with-dynamic-expression-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!