Direct SQL

LINQ to SQL is a part of the ADO.NET family of technologies. It is based on services provided by the ADO.NET provider model. Therefore, it is possible to mix LINQ to SQL code with existing ADO.NET applications. For example, you can create a DataContext using an existing ADO.NET connection.

In some cases, you might find that the query or submit changes facility of the DataContext is insufficient for the specialized task that you want to perform. In these cases, it is possible to use the DataContext to issue raw SQL commands directly to the database.

The ExecuteQuery() method lets you execute a raw SQL query, and converts the result of your query directly into objects.

The ExecuteCommand() method lets you directly execute SQL commands against the database.

For example, the following code will retrieve all discontinued products, and update the price for one product:

var products = db.ExecuteQuery<Product>(
"SELECT ProductID, ProductName " +
"FROM Products " +
"WHERE Discontinued = 0 " +
"ORDER BY ProductName;"
);
Console.WriteLine("Total discontinued products :{0}", products.Count());
int rowCount = db.ExecuteCommand(
" update products "
+ "set UnitPrice=UnitPrice+1 "
+ "where productID=35");
if (rowCount < 1)
Console.WriteLine("No product is updated");
else
Console.WriteLine("Product price is updated");
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset