"SELECT VALUE" - value keyword in LINQ/Entity Framework query

NealWalters picture NealWalters · Mar 13, 2013 · Viewed 17.8k times · Source

What does the keyword "value" mean in this statement, and where would I go to learn more?
What happens if I leave out the keyword "value"? In the code below, z is an entity framework class.

string queryString = "SELECT VALUE q from x.zs as q where q.a = @parm;"
ObjectQuery<z> query = context.CreateQuery<z> 
    (queryString, new ObjectParameter("parmname",parmvalue)); 
return query.First(); 

(This is a part of a practice question for an exam).

The above code is in a function that returns a variable of type z.

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Mar 13, 2013

That is Entity SQL syntax. Value keyword allows only one value to be specified, and does not add a row wrapper.

Read article about SELECT statement in ESQL

Entity SQL supports two variants of the SELECT clause. The first variant, row select, is identified by the SELECT keyword, and can be used to specify one or more values that should be projected out. Because a row wrapper is implicitly added around the values returned, the result of the query expression is always a multiset of rows.

Each query expression in a row select must specify an alias. If no alias is specified,Entity SQL attempts to generate an alias by using the alias generation rules.

The other variant of the SELECT clause, value select, is identified by the SELECT VALUE keyword. It allows only one value to be specified, and does not add a row wrapper.

So, if you want to materialize z object from your query, you should use SELECT VALUE syntax (otherwise you will get exception: cast from MaterializedDataRecord to z type is not valid).

Without VALUE keyword you will get set of rows:

string esql = "SELECT q from x.zs as q where q.a = @parm;";
ObjectQuery<DbDataRecord> query = context
       .CreateQuery<DbDataRecord>(esql, new ObjectParameter("parm",parmvalue)); 
var result = query.First();