Q:

Confusion regarding expression trees

I have read that expression trees are used to build dynamic queries. My confusion is that the same thing can be achieved through simple strings also. For example suppose here is a sample query to fetch products from a table:
string productName = Console.Read();
var result = from products in context.Products
             where product.Name.Equals(productName)
             select product;

Instead even if we use plain ADO.Net SQL provider,we can build dynamic query as follows:
string productName = Console.Read();
string query= "Select * from tableName where productname=" + productName;

Then what is the benefit of using Expression trees?
Similarly, while writing dynamic code using expression trees, can't we simply store our whole code as string and write custom parsing logic for evaluating it at runtime?
Infact, this question is not specific to expression trees but trees in general.

A:

This syntax can operate across CLR objects and relational database stacks. It is a well known query syntax that is translated into the correct query string for your database at run time. The advantage you get is that you can swap out your database tech and theoretically it just keeps working. As noted in the comments, you also get told about errors at compile time, not run time.

