我正在使用动态表达式 API (System.Linq.Dynamic
)与 LINQ to Entities。我的 LINQ 查询如下。
var query = this.db.Products.AsQueryable()
.Where(strCondition)
.OrderBy("ProductNumber")
.Select("new(ProductNumber, ProductDescription, ProductCategory.Name)");
现在我有了“查询”,我不知道如何获取每个字段的值。
string strTemp;
foreach (var item in query)
{
strTemp = item.?
}
它是匿名类型,所以我不能真正使用强类型来获取值。我能做些什么?我选择获取匿名类型字段的原因是因为我需要将 ProductCategory.Name 字段获取到结果中。有没有更好的方法使用动态表达式 API 在结果中获取 ProductCategory.Name?有人可以帮忙吗?
处理它的最简单方法是将循环变量声明为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");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)