Dynamic Properties in LinqConnect

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
Sograf
Posts: 2
Joined: Tue 26 Apr 2011 10:40
Location: De Bilt
Contact:

Dynamic Properties in LinqConnect

Post by Sograf » Tue 26 Apr 2011 11:26

My code attempted some reflection in a Linq query. Not surprisingly this resulted in a NotSupportedException. Unfortunately I have no appealing alternatives.

My current code:

Code: Select all

public static IEnumerable Find(int start, int limit, IEnumerable> filter)
        {
            var context = new DataContext();

            var query = context.OrderViews;

            foreach (var tuple in filter)
            {
                query = query.Where(o => tuple.Item2.Equals(o.GetType().GetProperty(tuple.Item1).GetValue(o, null)));
            }

            return query.Skip(start).Take(limit);
        }
A list of tuples is entered as a parameter. The first item is the name of a property and the second is the desired value. Somehow I need to transform this list into where clauses for the query. Obviously this is not the way.

One alternative I've considered was simply creating a where clause for each property in the entity, but that would leave me with a giant set of if statements, which does not really leave me with fuzzy happy feelings.

Another alternative suggested by someone, was to write an extension of sorts to provide the sql for this construction. I'm not really familiar with LinqConnect however and would even know where to begin.

Which would be the best approach to solve this problem? Or is there an other way I'm overlooking?

StanislavK
Devart Team
Posts: 1710
Joined: Thu 03 Dec 2009 10:48

Post by StanislavK » Wed 27 Apr 2011 10:16

To implement the scenario you've described, you can, e.g., use an overload of the Where extension method that receives a string parameter (i.e., a part of the 'where' clause):

Code: Select all

var query = context.OrderViews.Where(tuple.Item1 + " = @0", tuple.Item2);
For more information about implementing and using such extension methods, please refer to
http://weblogs.asp.net/scottgu/archive/ ... brary.aspx

Feel free to contact us if anything is unclear.

Sograf
Posts: 2
Joined: Tue 26 Apr 2011 10:40
Location: De Bilt
Contact:

Post by Sograf » Thu 28 Apr 2011 14:20

Thanks, it worked like a charm.

I've written and extension function that translates the filter tuples to linq expressions, based on the article and the example code.

Post Reply