2

I have a list of objects (say family), and each object contains a list of other non-value type object (say child). I would like to query this list and specify the where clause dynamically (during run-time).

var fselected = from f in families 
                from c in f.Children 
                where (f.FamilyAge > 15 && c.Age > 13) 
                select f;

The closest thing I found that would do that is Dynamic LINQ on NuGet, but beyond the simple where clause on the top level object, I can't find any examples on how to do above statement.

The only solution I can think of is to split into separate where clause for C and for F, run the c query first, then run F query on resultant data set...

AVSTR
  • 21
  • 5
  • 1
    Possible duplicate of [How to create LINQ Query from string?](http://stackoverflow.com/questions/5139467/how-to-create-linq-query-from-string) – Fruchtzwerg Dec 13 '16 at 17:56

1 Answers1

0

don't use strings to let your users create dynamic queries on your database, that will leave you vulnerable to sql injection. Instead, expose nullable parameters to your users

public Family GetFamily(int? familyAge, int? age)
{
    var families = GetAllFamilies();

    if(familyAge.HasValue)
        families = families.Where(x => x.familyAge = familyAge.value);

    if(age.HasValue)
        families = families.Where(x => x.age = age.value);

    return familes.ToList();
}

Update

Despite the problems of injections when using strings to let your users query your db, you can use the Dynamic Linq Library to pass on a string as a query. But I do advise against using this.

Stormhashe
  • 704
  • 6
  • 16
  • thanks for your reply. I provided an oversimplified case. Now imagine my family object has 20 properties, and child another 20, and I will keep adding properties in the future. I'd like to enable user to type in the query, on one, or two or all of them from a single line. Building UI to fit this scenario is not feasable. – AVSTR Dec 13 '16 at 18:07
  • Your laziness for coding all the scenarios the right way are no excuse for leaving your database open to your user. It's just wrong to do it. You will have to write all the scenarios nonetheless, either by wrongfully using strings, or correctly passing nullable parameters. – Stormhashe Dec 13 '16 at 19:06
  • while your code is safer for the database, it does not solve the problem at hand, which is to be able to generate queries at run-time. Consider something simple like this: familyAge>10 || familyAge<7 | familyAge=8. How many GetFamily functions are needed to do all the permutations? – AVSTR Dec 14 '16 at 00:22
  • Well, if you trully want to use strings, there's a library you can use. I'll update my answer – Stormhashe Dec 14 '16 at 14:06