【问题标题】:Select Anonymous type with Dynamic Expression API使用动态表达式 API 选择匿名类型
【发布时间】:2010-10-29 09:06:46
【问题描述】:

我正在将动态表达式 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?有人可以帮忙吗?

【问题讨论】:

    标签: c# dynamic linq-to-entities expression


    【解决方案1】:

    处理它的最简单方法是将循环变量声明为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");
    }
    

    【讨论】:

      【解决方案2】:

      只需使用您用于创建匿名对象的属性名称即可。 VS intellisense 应该会选择它们。

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

      您也可以指定自己的属性名称:

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

      【讨论】:

      • 问题是 VS intellisense 没有捡起来。我假设它是因为查询使用的是使用字符串值的动态表达式 API。有什么线索吗?
      • @Seecott - 你是对的。 VS不会接他们。看这里:weblogs.asp.net/scottgu/archive/2008/01/07/…
      • 我以前看过。那里没有答案。有谁知道如何或有示例代码来获取项目属性?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多