Just would like to know if its possible to do lazy loading without linq or an ORM. There are some queries I need to do that is inappropriate for ORMs. I will also need to pass the query between methods. Also, I could’t find any micro orms to achieve this. Is there any way to do this?
var q = "Select Name from Test1"
Now we must add an OR or AND or IN or something else
This query will be passed to different methods to be filtered. Is there a way to do this using a micro ORM or AD Hoc SQL Queries?
One approach is to express the query as some sort of in-memory object that you can further add expressions to it. For example, using some made up object hierarchy:
You would further refine this by adding filters:
But of course this means that you are re-inventing
IQueryable. You would better just embrace LINQ then and choose a provider (LINQ2SQL or LINQ2EF etc).Another approach is to keep the string ad-hoc representation:
but then how do you add a filter? You have to parse the string and insert the WHERE clause. This is far from trivial. You would soon be implementing a fully fledged SQL parser (lex+yacc or bison+flex) and a abstract syntax tree, and then serialize this as a new SQL string. Once you start thinking about joins (fairly trivial to support), subqueries (nasty), recursive table expressions (ouch) things get progresively more complex. Just browse this very site and look at how complex SQL queries can get, and imagine implementig a parse for that.
Many of projects I’ve seen tried to represent queries as some intermediate form, eg. a structure (list of fields, table name, list of WHERE conditions, list of ORDER BY clauses etc) and then add new entries in these list representation (Add a new entry in the WHERE list to add a new filter). But, in retrospect, these representations pale in comparison to what LINQ offers. I admit, LINQ is an all-or-nothing offering and you either commit yourself or not. But attempting to re-invent it only reveals the complexity of the problem. Today I would approach the problem from the other end: start with LINQ and try to keep it at bay, do not allow it to grow into a hideous monster of uncontrollable query generation tool in which every layer of the project adds some filter to the
IQueryableand then bomb the server with something that no optimizer could even untangle.PS. Why I Wrote AREL is a good read on this whole problem.