Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
48 views

Creating Client Data Applications - Linq

The document discusses using the LINQ to SQL Object Relational Designer (O/R Designer) to create an object model that maps to database objects. It describes dragging database tables and views onto the designer surface to generate entity classes mapped to those objects. It also discusses mapping stored procedures and functions to methods on the DataContext class. Finally, it provides a walkthrough of using the O/R Designer to create entity classes for customers and orders tables, display the data, add a LINQ query, and configure entity classes to use stored procedures for data handling.

Uploaded by

Tan Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Creating Client Data Applications - Linq

The document discusses using the LINQ to SQL Object Relational Designer (O/R Designer) to create an object model that maps to database objects. It describes dragging database tables and views onto the designer surface to generate entity classes mapped to those objects. It also discusses mapping stored procedures and functions to methods on the DataContext class. Finally, it provides a walkthrough of using the O/R Designer to create entity classes for customers and orders tables, display the data, add a LINQ query, and configure entity classes to use stored procedures for data handling.

Uploaded by

Tan Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Document made by Tan Nguyen 03/2013

LINQ to SQL

CREATING CLIENT DATA APPLICATIONS -(LINQ)


O/R Designer (Object Relational Designer)

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.

Opening O/R Designer

You can open the O/R Designer by adding a new LINQ to SQL Classes item to
a project.

Important note: The O/R Designer is a simple object relational


mapper because it supports only 1:1 mapping relationships. In other words, an
entity class can have only a 1:1 mapping relationship with a database table or
view. Complex mapping, such as mapping an entity class to a joined table, is not
currently supported. Additionally, the designer is a one-way code generator. This
means that only changes that you make to the designer surface are reflected in
the code file. Manual changes to the code file are not reflected in the O/R
Designer. Any changes that you make manually in the code file are overwritten
when the designer is saved and code is regenerated.

Page 1 of 17

Document made by Tan Nguyen 03/2013

LINQ to SQL

Creating and Configuring the DataContext


After you add a LINQ to SQL Classes item to a project and open the O/R Designer,
the empty design surface represents an empty DataContext ready to be configured.
The DataContext is configured with connection information provided by the first
item that is dragged onto the design surface. Therefore, the DataContext is
configured by using connection information from the first item dropped onto the
design surface.

Creating Entity Classes That Map to Database Tables and Views


You can create entity classes mapped to tables and views by dragging database
tables and views from Server Explorer/Database Explorer onto the O/R Designer. As
indicated in the previous section the DataContext is configured with connection
information provided by the first item that is dragged onto the design surface. If a
subsequent item that uses a different connection is added to the O/R Designer, you
can change the connection for the DataContext.

Creating DataContext Methods That Call Stored Procedures and


Functions
You can create DataContext methods that call (are mapped to) stored procedures
and functions by dragging them from Server Explorer/Database Explorer onto the
O/R Designer. Stored procedures and functions are added to the O/R Designer as
methods of the DataContext.

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.

Configuring a DataContext to Use Stored Procedures to Save Data


Between Entity Classes and a Database
As stated earlier, you can create DataContext methods that call stored procedures
and functions. Additionally, you can also assign stored procedures that can be used
for the default LINQ to SQL runtime behavior that performs Inserts, Updates, and
Deletes.

Inheritance and the O/R Designer


Page 2 of 17

Document made by Tan Nguyen 03/2013

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.

LINQ to SQL Queries


The entity classes created by the O/R Designer are designed for use with LanguageIntegrated Query (LINQ).

Separating the Generated DataContext and Entity Class Code into


Different Namespaces
The O/R Designer provides the Context Namespace and Entity Namespace
properties on the DataContext. These properties determine what namespace the
DataContext and entity class code is generated into. By default, these properties
are empty and the DataContext and entity classes are generated into the
application's namespace. To generate the code into a namespace other than the
application's namespace, enter a value into the Context Namespace and/or Entity
Namespace properties.

Page 3 of 17

Document made by Tan Nguyen 03/2013

LINQ to SQL

Walkthrough: Creating LINQ to SQL Classes


(O/R Designer)
.NET Framework 3.5
The Object Relational Designer (O/R Designer) provides a visual design surface for creating and
editing LINQ to SQL classes (entity classes) that are based on objects in a database. By using
LINQ to SQL, you can access SQL databases with LINQ technology. For more information, see
Language-Integrated Query (LINQ).
This walkthrough provides the steps that you must follow to create LINQ to SQL entity classes
mapped to the Customers and Orders tables in the Northwind database and display the data on a
Windows Form. In addition to the steps for displaying the data from the table, the steps for
binding data to a LINQ query are also provided. Finally, the steps for using stored procedures to
replace the default LINQ to SQL logic for sending updates from the entity classes to the database
are provided.
During this walkthrough, you will learn how to perform the following tasks:

Add a LINQ to SQL file to a project.

Create new entity classes that are mapped to related tables in the database.

Create an object data source that references the entity classes.

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.

Add stored procedures to the O/R Designer.

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

Document made by Tan Nguyen 03/2013

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.

Creating the Windows-Based Application


Because you will be working with LINQ to SQL classes and displaying the data on a Windows
Form, the first step in this walkthrough is to create a new Windows Forms application.
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.

To create the new Windows Application project


1. From the File menu, create a new project.
2. Name the project ORDesignerWalkthrough.
Note:
The O/R Designer is supported in Visual Basic and C# projects, so create the new project in one
of these languages.
3. Click the Windows Forms Application template and click OK. For more information, see
Creating Windows-Based Applications.
The ORDesignerWalkthrough project is created and added to Solution Explorer.
Adding a LINQ to SQL Classes File to the Project (Opening the O/R Designer)
Entity classes are created and stored in LINQ to SQL Classes files (.dbml files). The O/R
Designer opens when you open a .dbml file. Add .dbml files to projects by selecting the LINQ to
SQL Classes template in the Add New Item dialog box.

To add a .dbml file to a project


Page 5 of 17

Document made by Tan Nguyen 03/2013

LINQ to SQL

1. On the Project menu, click Add New Item.


2. Click the LINQ to SQL Classes template and type Northwind.dbml in the Name box.
3. Click Add.
An empty LINQ to SQL Classes file (Northwind.dbml) is added to the project, and the
O/R Designer opens.
After you add the new LINQ to SQL file to the project, the empty design surface opens,
displaying two separate panes. The pane on the left is the entities pane, where entity classes are
displayed and configured. The pane on the right is the methods pane that displays the
DataContext methods added to the designer. If the methods pane is not visible right click an
empty area in the entities pane and click Show Methods Pane. The entire empty surface
represents a DataContext ready to be configured. The DataContext name corresponds to the
name that you provided for the .dbml file. For this walkthrough, because you named the LINQ to
SQL file Northwind.dbml, the DataContext is named NorthwindDataContext. You can verify this
by clicking any empty area on the designer and inspecting the Properties window.
Note:
The DataContext class contains methods and properties for connecting to a database and
manipulating the data in the database (for example, performing Inserts, Updates, and Deletes).
For more information, see DataContext Methods (O/R Designer).
Creating Customer and Order Entity Classes
Create LINQ to SQL classes that are mapped to database tables by dragging tables from Server
Explorer/Database Explorer onto the O/R Designer. The result is a LINQ to SQL entity class that
maps to the table in the database.

To add a Customer entity class to the O/R Designer


1. In Server Explorer/Database Explorer, locate the tables in the SQL Server version of the
Northwind sample database. For more information, see How to: Create a Data
Connection to the Northwind Database.
2. Drag the Customers node from Server Explorer/Database Explorer onto the O/R Designer
surface.
An entity class named Customer is created. It has properties that correspond to the
columns in the Customers table. The entity class is named Customer (not Customers)
because it represents a single customer from the Customers table.
Note:
Page 6 of 17

Document made by Tan Nguyen 03/2013

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

Document made by Tan Nguyen 03/2013

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.

To add controls bound to the entity classes


1. Open Form1 in Design view.
2. From the Data Sources window, drag the Customer node onto Form1.
Note:
To display the Data Sources window, click Show Data Sources on the Data menu.
3. Drag the Orders node from the Data Sources window onto Form1. Place it under
CustomerDataGridView.
4. Open Form1 in code view.
5. Add the following code to the form, global to the form, outside any specific method, but
inside the Form1 class:
VB
Private NorthwindDataContext1 As New NorthwindDataContext

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

Document made by Tan Nguyen 03/2013

LINQ to SQL

CustomerBindingSource.DataSource = NorthwindDataContext1.Customers

C#
customerBindingSource.DataSource
= northwindDataContext1.Customers;

Testing the Application


Run the application. At this point the form contains one DataGridView displaying the data from
the Customers table and a second DataGridView displaying the data from the selected customer's
orders.
Note:
Notice that the save button is disabled. (You will implement save functionality in the next
section.)

To test the application


1. Press F5.
2. Verify that data appears in the grids.
3. Select a customer.
4. Verify that the orders displayed are for the selected customer.
5. Close the form. (On the Debug menu, click Stop Debugging.)
Implementing Save Functionality
As noted earlier, by default the save button is not enabled, and save functionality is not
implemented. Also, code is not automatically added to save changed data to the form when databound controls are created for object data sources. This section explains how to enable the save
button and implement save functionality for LINQ to SQL objects.

To implement save functionality


1. Open Form1 in Design view.
2. Select the save button on the CustomerBindingNavigator. (The button labeled with a
floppy disk icon.)

Page 9 of 17

Document made by Tan Nguyen 03/2013

LINQ to SQL

3. In the Properties window, set the Enabled property to True.


4. Double-click the save button to create an event handler and switch to the Code Editor.
5. Add the following code into the save button event handler:
VB
Try

NorthwindDataContext1.SubmitChanges()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

C#
try
{

northwindDataContext1.SubmitChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Testing the Application


Run the application. The save button should be enabled, and the ability to save data is available.

To test the application


1. Press F5.
2. Modify some data in either grid. (Navigate off the edited row in the grid to commit inprocess changes.)
3. Click the save button to save changes back to the database.
4. Close the form.
5. Press F5 and verify that the changes were persisted (or locate the table in the database to
verify that the changes were saved).
Binding to LINQ Queries
In addition to binding the CustomerBindingSource to the DataContext, you can also bind directly
to LINQ queries. For more information about how to create LINQ queries, see Introduction to
LINQ Queries.
Page 10 of 17

Document made by Tan Nguyen 03/2013

LINQ to SQL

Adding a Button and TextBox to the Form


To learn how to bind controls to LINQ queries, add controls to the form that enable you to enter
a query parameter and then run the query.

To add controls to the form


1. Open Form1 in Design view.
2. Add a TextBox to the form and set its Name property to CityTextBox.
3. Add a Button to the form and set the following properties:
o Name = RunQueryButton
o Text = Run Query

Data Binding to the LINQ Query


Add code to run a LINQ query. The query uses the value typed into CityTextBox as a query
parameter.

To bind to a LINQ query

Double-click the RunQueryButton and add the following code to the


RunQueryButton_click event handler:
VB
Dim CustomersQuery = From customers in NorthwindDataContext1.Customers _
Where customers.City = CityTextBox.Text _
Select customers
CustomerBindingSource.DataSource = CustomersQuery

C#
var CustomersQuery = from customers in northwindDataContext1.Customers
where customers.City == CityTextBox.Text
select customers;
customerBindingSource.DataSource = CustomersQuery;

Testing the Application


Run the application. You can now query for customers in a specific city.

To test the application


Page 11 of 17

Document made by Tan Nguyen 03/2013

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.

To override the default update behavior


1. Open the LINQ to SQL file in the O/R Designer. (Double-click the Northwind.dbml file
in Solution Explorer.)
2. In Server Explorer/Database Explorer, expand the Northwind databases Stored
Procedures node and locate the UpdateCustomers stored procedure.
3. Drag the UpdateCustomers stored procedure onto the O/R Designer.
The UpdateCustomers stored procedure is added to the methods pane as a DataContext
method. For more information, see DataContext Methods (O/R Designer).
4. Select the Customer entity class in the O/R Designer.
5. In the Properties window, select the command to override. (Insert, Update, or Delete). For
this example, select the Update property.
Page 12 of 17

Document made by Tan Nguyen 03/2013

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.

To test the application


1. Press F5.
2. Locate the ContactName column in the grid for ALFKI.
3. Change the name from Maria Anders to Anders.
4. Navigate off the row to commit the change.
5. Click the save button.
6. Close the form.

Page 13 of 17

Document made by Tan Nguyen 03/2013

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

Document made by Tan Nguyen 03/2013

LINQ to SQL

How to: Assign Stored Procedures to Perform


Updates, Inserts, and Deletes (O/R Designer)
.NET Framework 3.5
10 out of 12 rated this helpful - Rate this topic
Stored procedures can be added to the O/R Designer and executed as typical DataContext
methods. They can also be used to override the default LINQ to SQL runtime behavior that
performs Inserts, Updates, and Deletes when changes are saved from entity classes to a database
(for example, when calling the SubmitChanges method).
Note:
If your stored procedure returns values that need to be sent back to the client (for example,
values calculated in the stored procedure), create output parameters in your stored procedures. If
you cannot use output parameters, write a partial method implementation instead of relying on
overrides generated by the O/R Designer. Members mapped to database-generated values need
to be set to appropriate values after successful completion of INSERT or UPDATE operations.
For more information, see Responsibilities of the Developer In Overriding Default Behavior
(LINQ to SQL).
Note:
LINQ to SQL handles database-generated values automatically for identity (auto-increment),
rowguidcol (database-generated GUID), and timestamp columns. Database-generated values in
other column types will unexpectedly result in a null value. To return the database-generated
values, you should manually set IsDbGenerated to true and AutoSync to one of the
following: Always, OnInsert, or OnUpdate.
Configuring the Update Behavior of an Entity Class
By default, the logic to update a database (Inserts, Updates, and Deletes) with changes that were
made to the data in LINQ to SQL entity classes is provided by the LINQ to SQL runtime. The
runtime creates default Insert, Update, and Delete commands that are based on the the schema of
the table (the column and primary key information). When the default behavior is not desired,
you can configure the update behavior by assigning specific stored procedures for performing the
necessary Inserts, Updates, and Deletes required to manipulate the data in your table. You can
also do this when the default behavior is not generated, for example, when your entity classes
map to views. Finally, you can override the default update behavior when the database requires
table access through stored procedures.
Page 15 of 17

Document made by Tan Nguyen 03/2013

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.

To assign stored procedures to override the default behavior of an entity class


1. Open the LINQ to SQL file in the designer. (Double-click the .dbml file in Solution
Explorer.)
2. In Server Explorer/Database Explorer, expand Stored Procedures and locate the stored
procedures that you want to use for the Insert, Update, and/or Delete commands of the
entity class.
3. Drag the stored procedure onto the O/R Designer.
The stored procedure is added to the methods pane as a DataContext method. For more
information, see DataContext Methods (O/R Designer).
4. Select the entity class for which you want to use the stored procedure for performing
updates.
5. In the Properties window, select the command to override (Insert, Update, or Delete).
6. Click the ellipsis (...) next to the words Use Runtime to open the Configure Behavior
dialog box.
7. Select Customize.
8. Select the desired stored procedure in the Customize list.
9. Inspect the list of Method Arguments and Class Properties to verify that the Method
Arguments map to the appropriate Class Properties. Map the original method arguments
(Original_ArgumentName) to the original properties (PropertyName (Original)) for
Update and Delete commands.
Note:
By default, method arguments map to class properties when the names match. If changed
property names 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.
10. Click OK or Apply.
Page 16 of 17

Document made by Tan Nguyen 03/2013

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.

How to: Query for Information (LINQ to


SQL)
.NET Framework 3.5
Queries in LINQ to SQL use the same syntax as queries in LINQ. The only difference is that
the objects referenced in LINQ to SQL queries are mapped to elements in a database. For
more information, see Introduction to LINQ Queries.
LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to
the server for processing.
Some features of LINQ queries might need special attention in LINQ to SQL applications.
For more information, see Query Concepts in LINQ to SQL.
Example
The following query asks for a list of customers from London. In this example, Customers is
a table in the Northwind sample database.
C#
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
// Query for customers in London.
IQueryable<Customer> custQuery =
from cust in db.Customers
where cust.City == "London"
select cust;

Page 17 of 17

You might also like