Can I execute a scalar query in EF 4.1?

試著忘記壹切 提交于 2019-12-12 03:09:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!