I am working in Linq Now I want开发者_JAVA百科s to know that which is better then from the following to run a sql query.
1) ExecuteQuery
2) ExecuteCommand
Both methods ExecuteQuery and ExecuteCommand are methods of the LINQ DataContext. They are pass-through mechanisms for cases where LINQ to SQL does not adequately provide for a particular scenario. It would be rare that you would use these methods in LinqToSql because you would be losing the expressive power of LINQ which is the main reason for using LINQ. You would also be losing the value of having strongly-typed variables in your queries, which is the other main advantage to using LINQ.
It is considered poor programming practice to construct SQL Query strings and pass them directly to the database, because SQL commands which are constructed from string elements have been the pathway to database hacking called SQL injection. So in general, it would be advised to avoid using ExecuteQuery and ExecuteCommand, except when absolutely necessary and with great caution.
Now that I said all that, here is the explanation of when those methods would be used. ExecuteQuery would be used to perform a Select statement, while ExecuteCommand would be used to perform Insert, Update, Delete or for calling a stored procedure.
However, you should be using LINQ query syntax or LINQ lambda syntax for making your SQL calls, and not using ExecuteQuery or ExecuteCommand.
You can see ExecuteCommand return type is int so this may be used if you want to truncate table/DROP DATABASE/identity reset or check the current value/set ANSI nulls (where results are returned back). ExecuteQuery return type is IEnumerable so it is used in cases where the SQL statement that you provide returns a record set.
Please add your comments if anyone has more insights.
精彩评论