What You Can Do With LINQ to SQL
LINQ to SQL supports all the key capabilities you would expect as a SQL developer. You can query for information, and insert, update, and delete information from tables.
Selecting
Selecting (projection) is achieved by just writing a LINQ query in your own programming language, and then executing that query to retrieve the results. LINQ to SQL itself translates all the necessary operations into the necessary SQL operations that you are familiar with. For more information,
In the following example, the company names of customers from London are retrieved and displayed in the console window.
| Visual Basic | |
|---|---|
' Northwnd inherits from System.Data.Linq.DataContext. | |
| C# |
|---|
// Northwnd inherits from System.Data.Linq.DataContext. |
Inserting
To execute a SQL Insert, just add objects to the object model you have created, and call
In the following example, a new customer and information about the customer is added to the Customers table by using
' Northwnd inherits from System.Data.Linq.DataContext. | |||
| C# | |
|---|---|
// Northwnd inherits from System.Data.Linq.DataContext. | |
Updating
To Update a database entry, first retrieve the item and edit it directly in the object model. After you have modified the object, call
In the following example, all customers who are from London are retrieved. Then the name of the city is changed from "London" to "London - Metro". Finally,
| Visual Basic | |
|---|---|
Dim nw As New Northwnd("c:\northwnd.mdf") | |
| C# | |
|---|---|
Northwnd nw = new Northwnd(@"northwnd.mdf"); | |
Deleting
To Delete an item, remove the item from the collection to which it belongs, and then call
| Note: |
|---|
| LINQ to SQL does not recognize cascade-delete operations. If you want to delete a row in a table that has constraints against it. |
In the following example, the customer who has CustomerID of 98128 is retrieved from the database. Then, after confirming that the customer row was retrieved,
| Visual Basic | |
|---|---|
Dim nw As New Northwnd("c:\northwnd.mdf") | |
Northwnd nw = new Northwnd(@"northwnd.mdf"); | |
Comments
Post a Comment