Creating Client Data Applications - Linq
Creating Client Data Applications - Linq
LINQ to SQL
O/R Designer provides a visual design surface for creating LINQ to SQL entity
classes and associations (relationships) based on objects in a database. In
other words, the O/R Designer is used to create an object model in an
application that maps to objects in a database.
It also generates a strongly-typed DataContext that is used to send and
receive data between the entity classes and the database.
The O/R Designer also provides functionality to map stored procedures and
functions to DataContext methods for returning data and populating entity
classes.
Finally, the O/R Designer provides the ability to design inheritance
relationships between entity classes.
The O/R Designer generates the .dbml file that provides the mapping
between the LINQ to SQL classes and database objects. The O/R Designer
also generates the typed DataContext and the entity classes.
The O/R Designer has two distinct areas on its design surface: the entities
pane on the left, and the methods pane on the right. The entities pane is the
main design surface that displays the entity classes, associations, and
inheritance hierarchies. The methods pane is the design surface that displays
the DataContext methods that are mapped to stored procedures and
functions.
You can open the O/R Designer by adding a new LINQ to SQL Classes item to
a project.
Page 1 of 17
LINQ to SQL
Note:
When you drag stored procedures and functions from Server Explorer/Database
Explorer onto the O/R Designer, the return type of the generated
DataContext method differs depending on where you drop the item.
LINQ to SQL
Like other objects, LINQ to SQL classes can use inheritance and be derived from
other classes. In a database, inheritance relationships are created in several ways.
The O/R Designer supports the concept of single-table inheritance as it is often
implemented in relational systems.
Page 3 of 17
LINQ to SQL
Create new entity classes that are mapped to related tables in the database.
Create a Windows Form containing controls that are bound to entity classes.
Add code to load and save the data between the entity classes and the database.
Construct a simple LINQ query and display the results on the form.
Configure an entity class to use stored procedures to perform Inserts, Updates, and
Deletes.
Prerequisites
To complete this walkthrough, you need the following:
Page 4 of 17
LINQ to SQL
Access to the SQL Server version of the Northwind sample database. For more
information, see How to: Install Sample Databases.
The UpdateCustomer stored procedure for the Northwind database. For more
information, see Walkthrough: Creating Update Stored Procedures for the Northwind
Customers Table.
LINQ to SQL
LINQ to SQL
This renaming behavior is called pluralization. It can be turned on or off in the Options Dialog
Box (Visual Studio). For more information, see How to: Turn Pluralization On and Off (O/R
Designer).
3. Drag the Orders node from Server Explorer/Database Explorer onto the O/R Designer
surface.
An entity class named Order is created, along with a Customer_Order association
(relationship) to the Customer entity class. It has properties that correspond to the
columns in the Orders table.
Note:
The entity class is named Order because it represents a single order. The parent class (Customer)
has an Orders property that represents the collection of orders for that specific customer. For
more information about LINQ to SQL associations, see How to: Create an Association
(Relationship) Between LINQ to SQL Classes (O/R Designer).
Creating an Object Data Source with the Customer Entity Class
Entity classes, just like other classes that have public properties, can be used as object data
sources. They can be added to the Data Sources window and dragged onto forms to create databound controls (controls that are bound to the values in the public properties of the object). Add
entity classes to the Data Sources window by running the Data Source Configuration Wizard and
clicking Object for the data source in the wizard.
To add the Customer as an object data source in the Data Sources window
1. On the Build menu, click Build ORDesignerWalkthrough to build the project.
2. On the Data menu, click Show Data Sources.
3. In the Data Sources window, click Add New Data Source.
4. Click Object on the Choose a Data Source Type page and then click Next.
5. Expand the ORDesignerWalkthrough node (the node with the name of your project) and
locate and select the Customer class.
Note:
If the Customer class is not available, cancel out of the wizard, build the project, and run the
Page 7 of 17
LINQ to SQL
wizard again.
6. Click Finish to create the data source and add the Customer entity class to the Data
Sources window.
Creating Data-Bound Controls to Display the Data on a Windows Form
Create controls that are bound to entity classes by dragging LINQ to SQL data source items from
the Data Sources window onto a Windows Form.
C#
private NorthwindDataContext northwindDataContext1
= new NorthwindDataContext();
6. Create an event handler for the Form_Load event and add the following code to the
handler:
VB
Page 8 of 17
LINQ to SQL
CustomerBindingSource.DataSource = NorthwindDataContext1.Customers
C#
customerBindingSource.DataSource
= northwindDataContext1.Customers;
Page 9 of 17
LINQ to SQL
NorthwindDataContext1.SubmitChanges()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
C#
try
{
northwindDataContext1.SubmitChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
LINQ to SQL
C#
var CustomersQuery = from customers in northwindDataContext1.Customers
where customers.City == CityTextBox.Text
select customers;
customerBindingSource.DataSource = CustomersQuery;
LINQ to SQL
1. Press F5.
2. Type London in the text box.
3. Click the Run Query button.
4. Verify that only customers who have a value of London in their City property are
displayed.
Overriding the Default Behavior for Performing Updates (Inserts, Updates, and Deletes)
By default, the logic to perform updates is provided by the LINQ to SQL runtime. The runtime
creates default Insert, Update, and Delete statements based on the Select statement that is used to
populate your entity class with data. When you do not want to use the default behavior, you can
configure the update behavior and designate specific stored procedures for performing the
necessary Inserts, Updates, and Deletes required to manipulate the data in your database. You can
also do this when the default behavior is not generated, for example, when your entity classes
map to joined tables. Additionally, you can override the default update behavior when the
database requires table access through stored procedures.
Note:
This section requires the availability of the additional InsertCustomer, UpdateCustomer, and
DeleteCustomer stored procedures for the Northwind database. For details about how to create
these stored procedures, see Walkthrough: Creating Update Stored Procedures for the Northwind
Customers Table.
LINQ to SQL
6. Click the ellipsis next to Use Runtime to open the Configure Behavior dialog box.
7. Select Customize.
8. Select the UpdateCustomers method in the Customize list.
9. Inspect the list of Method Arguments and Class Properties and notice that there are two
Method Arguments and two Class Properties for some columns in the table. This
facilitates tracking changes and creating statements that check for concurrency violations.
10. Map the original method arguments (Original_ArgumentName) to the original properties
(PropertyName (Original)). For this walkthrough, you have to map the
Original_CustomerID argument to the CustomerID (Original) property.
Note:
By default, method arguments will map to class properties when the names match. If property
names were changed and no longer match between the table and the entity class, you might have
to select the equivalent class property to map to if the designer cannot determine the correct
mapping. Additionally, if method arguments do not have valid class properties to map to, you
can set the Class Properties value to (None).
11. Click OK.
Testing the Application
Run the application again to verify that the UpdateCustomers stored procedure correctly updates
the customer record on the database.
Page 13 of 17
LINQ to SQL
7. Press F5 to run the application again and verify that only Anders appears in the
ContactName column for ALFKI.
Next Steps
Depending on your application requirements, there are several steps that you may want to
perform after you create LINQ to SQL entity classes. Some enhancements you could make to
this application include the following:
Adding more stored procedures to use for the Insert and Delete commands. For more
information, see How to: Assign Stored Procedures to Perform Updates, Inserts, and
Deletes (O/R Designer).
Construct various LINQ queries to return filtered data. For more information, see How
to: Query for Information (LINQ to SQL).
Page 14 of 17
LINQ to SQL
LINQ to SQL
Note:
Your computer might show different names or locations for some of the Visual Studio user
interface elements in the following instructions. The Visual Studio edition that you have and the
settings that you use determine these elements. For more information, see Visual Studio Settings.
LINQ to SQL
Note:
You can continue to configure the behavior for each class/behavior combination as long as you
click Apply after you make each change. If you change the class or behavior before you click
Apply, a warning dialog box providing an opportunity to apply any changes will appear.
11. To revert to using the default runtime logic for updates, click the ellipsis next to the
Insert, Update, or Delete command in the Properties window and then select Use runtime
in the Configure Behavior dialog box.
Page 17 of 17