Difference between ExecuteSqlCommand and SqlQuery in ASP.Net Entity Framework

on Oct 21, 2020 10:44 AM

What is the difference between ExecuteSqlCommand vs SqlQuery ?

What is the best option to use on which condition.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Oct 22, 2020 05:15 AM

Hi rani,

ExecuteSqlCommand and SqlQuery both allow to use Entity Framework to execute raw SQL queries.

Generally, the SqlQuery method is used for actual queries where you expect data to be returned (i.e. SELECT statements) and SqlCommands are going to be more commonly used for non-queries (i.e. Insert, Update and Delete).

The ExecuteSqlCommand() method will return the number of rows affected by the query, whereas SqlQuery returns a value of any type (a collection of entities or objects) for the given query.



var customers = Context.Customers.SqlQuery("SELECT * FROM Customers").ToList();


var rowsAffected = Context.Database.ExecuteSqlCommand("INSERT INTO Customers (Name) VALUES ('Dharmendra'));