.NET 3.5's LINQ-to-SQL functionality provides a great way to write data access layer code that automatically handles mapping relational data to object properties. Although I generally prefer to use stored procedures when performing insert, update, or delete operations against a database, I still use LINQ-to-SQL in projects since it eliminates the time I used to spend creating SqlParameter objects or writing AddWithValue() parameter statements. Overall, LINQ-to-SQL has made me much more productive as a developer.
Most of the samples involving LINQ-to-SQL involve using the designer built-into Visual Studio 2008 since it's very productive. The LINQ-to-SQL designer is a great way to go and normally what I use when doing my Object-Relational Mapping (ORM). I recently had someone ask if using the LINQ-to-SQL designer was required to leverage LINQ-to-SQL in their applications. They had existing data entity classes that they wanted to use and didn't want to re-create them using the designer. In situations like this you can use built-in XML mapping features available in LINQ-to-SQL to get around using the designer if desired. Going this route leads to writing more custom code and XML mapping files but also provides the ultimate in control especially if your data entity classes are created by another tool, you don't want your classes littered with LINQ-to-SQL attributes, or you have some other reason for not wanting to use the designer. In this article, I provide a step-by-step introduction to working with LINQ-to-SQL XML mapping files. The sample code that accompanies this article is available here.
Step 1. Create the Data Entity Class
If you're not using the LINQ-to-SQL designer, then you'll need to create your own data entity classes (or use third-party tools to create them) that can hold data from the target database. If you already have existing data entity classes that you want to use then you can skip this step. Here's a simple Customer class capable of holding some of the data found in the Customer table in the AdventureWorksLT database.
namespace Model { public class Customer { public int CustomerID { get; set; } public string Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime ModifiedDate { get; set; } } }
A diagram of the Customer table follows: