DISQUS

Emad Ibrahim: Dynamically Build LINQ Queries Using Reflection

  • Mark S. Rasmussen · 1 year ago
    I don't get it. How is this preferred over just doing a DataContext.Translate()?

    Also, your dynamicClass string generation could be rewritten as a much simpler one-liner:
    string dynamicClass = "new(" + string.Join(",", columnsToExport) + ")";

    I'm assuming you validate for a positive number of selected columns somewhere else.
  • Mark S. Rasmussen · 1 year ago
    I see that you do not need a strongly typed result at all which'll also render DataContext.Translate() unnessesary. Why go through this hassle and not just execute a command directly?
  • Emad Ibrahim · 1 year ago
    @mark: Thanks for pointing out the Translate() method, I looked into it and that wouldn't solve my problem. For starters using reflection works well for me because I can dynamically populate the list of columns in a checkboxlist and then dynamically create the LINQ query...

    Using reflection and custom attribute also allowed me to specify which columns can be exported and which ones can't. So that alone, would prevent me from using regular sql strings and executing on a command.

    On the other hand, you are right, almost everything I did could have been done with a sql string and a command but where is the fun in that :)

    Thanks for the string.Join... I am embarrassed to say that I have never used it before and looking at your code snippet - I LOVE IT.
  • kashifpervaiz · 2 months ago
    Nice article. Quick question: if i want to pass the results of the query which is in data access layer to business then to UI, what would be the return type?
  • eibrahim · 2 months ago
    Honestly, it has been so long since I posted this and I can't remember but
    if you do find, please come back and let us know. It will help future
    readers.
    Thanks.