【问题标题】:Need help building LINQ to SQL Expression需要帮助构建 LINQ to SQL 表达式
【发布时间】:2009-11-16 19:20:20
【问题描述】:

我需要将下面的代码翻译成一个表达式,我会解释原因:

results = results.Where(answer => answer.Question.Wording.Contains(term));

结果是 IQueryable
问题是 ISurveyQuestion
措辞是字符串

问题是,问题并不总是 LINQ to SQL 属性的名称。

这将为我提供实际 ISurveyQuestion 属性的 PropertyInfo

private static PropertyInfo FindNaturalProperty<TMemberType>(Type search)
{
    IDictionary<string,PropertyInfo> properties = new Dictionary<string,PropertyInfo>();

    search.GetProperties().Each(prop =>
    {
        if (null != prop.PropertyType.GetInterface(typeof(TMemberType).Name))
            properties.Add(prop.Name, prop);
    });

    if (properties.Count < 1) throw new ArgumentException(String.Format("{0} has no properties of type {1}", search.Name, typeof(TMemberType).Name));
    if (properties.Count == 1) return properties.Values.First();

    search.GetInterfaces().Each(inter =>
    {
        inter.GetProperties().Each(prop =>
        {
            if (null != prop.PropertyType.GetInterface(typeof(TMemberType).Name))
                properties.Remove(prop.Name);
        });
    });

    if (properties.Count < 1) throw new ArgumentException(String.Format("{0} has no properties of type {1} that are not members of an interface", search.Name, typeof(TMemberType).Name));
    if (properties.Count > 1) throw new AmbiguousMatchException(String.Format("{0} has more than one property that are of type {1} and are not members of an interface", search.Name, typeof(TMemberType).Name));


    return properties.Values.First();
}

获得 PropertyInfo 后,如何将其转换为表达式树?

编辑:

我基本上需要的是:

results = results.Where(answer => answer.GetQuestionProperty().GetValue(answer).Wording.Contains(term));

但这不起作用,所以我需要自己构建表达式树,用于 linq-to-sql。

【问题讨论】:

    标签: linq-to-sql lambda expression-trees


    【解决方案1】:

    阅读我认为您所追求的问题是 Dynamic Linq - 这是一个帮助程序库,可让您使用字符串而不是在设计时动态构建 Linq 查询(!)。这意味着,如果您可以获得您的属性名称,您应该能够即时创建您的查询。

    ScottGu 有一篇文章here

    【讨论】:

    • 我们都上了 ScottGu 的博客 :)
    【解决方案2】:

    您尝试做的是创建一个动态查询,并且您希望查询所针对的操作表/属性也是动态的。根据您的使用方式,我不确定这是否容易实现。

    查看 ScottGu 的博文: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

    查看 Rick Strahl 的博文: http://www.west-wind.com/Weblog/posts/143814.aspx

    【讨论】:

    • 啊哈!这绝对看起来像答案。谢谢!不幸的是,只有一个绿色复选标记,墨菲第一个回答:(
    • results.ElementType 应该让我可以访问我正在寻找的 PropertyInfo。然后 DynamicLinq 应该为我构建表达式......我想。
    【解决方案3】:

    http://www.linqpad.net/

    linqpad 会为你转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多