1

Is there a way that I can access a LINQ property dynamically using a variables value without reflection in vanilla C#? I believe there are some libraries that could assist in this (such as System.Linq.Dynamic), but I would like to avoid a dependency if possible. In pseudo, something that functions like this:

var temp = "PropertyName";
context.Table.Where(a => a.GetProperty(temp) > 5);

I initially tried a solution like this using reflection, which worked perfectly when I was testing it with regular LINQ. However it doesn't work with a LINQ-to-Entity object, since EF can't compile that into SQL. I also looked into expression trees, but that didn't seem like the way to go for just the property accessing capabilities (and some of my "Where" conditions are going to be dynamically generated).

If anyone has any ideas / examples on this, I'd appreciate it!

mju516
  • 125
  • 2
  • 9

1 Answers1

0

If you don't want to use Expression (which is probably the proper way) and you don't want to depend on System.Linq.Dynamic (which is Expression done for you) then you can go old school since you presumably know the column names:

var query = context.Table.AsQueryable();

switch (temp) {
    case "PropertyName1":
        query = query.Where(a => a.PropertyName1 > 5);
        break;
    case "PropertyName2":
        query = query.Where(a => a.PropertyName2 > 15);
        break;
}
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • Actually I would be getting the names dynamically as well haha, but this would work, so I'm marking it. I wound up going with System.Linq.Dynamic. – mju516 Jul 18 '17 at 23:58