问题
Is it possible to execute a scalar-valued query using EF 4.1?
I've tried:
ObjectQuery<int> query = new ObjectQuery<int>("select count(*) from myTable", _context);
var result = query.Execute(MergeOption.NoTracking);
return result.FirstOrDefault();
but it returns an error: The query syntax is not valid. Near term '*'
Is the only way to execute a scalar-valued query to call a stored proc?
回答1:
It seems to me that you are thinking of entity framework as an "ADO.net 2.0" rather than the ORM that it is.
Rather than using it to execute SQL queries, I'd recommend using the standard entity framework Data container and using a LINQ query, as is intended with entity framework. Then it would simply be something like
myDataContainerInstance.myTable.Count()
ObjectQuery isn't analogous to the ADO.net command and doesn't execute SQL statements. Instead it is used to define queries against the object model directly. The (*) isn't valid because it isn't SQL.
来源:https://stackoverflow.com/questions/9569396/can-i-execute-a-scalar-query-in-ef-4-1