Search code examples
linq-to-sqllambdaexpression-trees

Need help building LINQ to SQL Expression


I need to translate the following Code to an Expression and I will explain why:

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

results is IQueryable<ISurveyAnswer>
Question is ISurveyQuestion
Wording is String

The problem is, Question is not always the name of the LINQ to SQL property.

This will give me the PropertyInfo for the actual ISurveyQuestion property

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();
}

Once I have the PropertyInfo how do I translate that to an Expression Tree?

EDIT:

What I basically need is:

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

But that doesn't work so I need to build the Expression Tree myself, for linq-to-sql.


Solution

  • Reading the question I think what you're after is Dynamic Linq - which is a helper library to let you build Linq queries dynamically (!) using strings as opposed to at design time. That means that if you can get your property name you should be able create your query on the fly.

    ScottGu has an article here