LINQ to SQL allows you to execute raw SQL queries directly against the database where you cannot use LINQ to represent the query and the generated SQL is not efficient enough.
DataContext.ExecuteQuery()
method to execute a raw SQL query.
using (var db = new CustomerContext(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=CustomerContext;"))
{
var results = db.ExecuteQuery<Customer>("SELECT * FROM Customers ORDER BY FirstName;");
foreach (var customer in results)
{
Console.WriteLine(customer.FirstName + ", " + customer.LastName);
}
}
The ExecuteQuery method also supports a parameterized query.
using (var db = new CustomerContext(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=CustomerContext;"))
{
string firstName = "Maria";
var results = db.ExecuteQuery<Customer>("SELECT * FROM Customers Where FirstName = {0} ORDER BY FirstName;", firstName);
foreach (var customer in results)
{
Console.WriteLine(customer.FirstName + ", " + customer.LastName);
}
}