Step 5. Query the Database Using the DataContext Object
Once the XML mapping file is loaded into the DataContext object you can query the database using LINQ or Lambda expressions. Here's an example of grabbing all of the customer records that have a last name starting with "M":
IEnumerable<DAL.Customer> custs = from c in context.GetTable<DAL.Customer>() where c.LastName.StartsWith("M") select c; foreach (DAL.Customer cust in custs) { Console.WriteLine(cust.FirstName + " " + cust.LastName); }
The ap_GetCustomerByLastName stored procedure can be called using the CustomDataContext object's GetCustomerByLastName() method as shown next:
IEnumerable<DAL.Customer> custs2 = context.GetCustomerByLastName("A"); foreach (DAL.Customer cust in custs2) { Console.WriteLine(cust.FirstName + " " + cust.LastName); }
The results of the two queries are shown next:
Conclusion
Although the LINQ-to-SQL designer provides the biggest bang for the buck as far as productivity goes when working with LINQ-to-SQL, the XML mapping features discussed here (although not as productive from a time standpoint) let you have more control over the classes that are used in an application and the manner in which they're mapped to database tables. Regardless of which route you choose to go, LINQ-to-SQL will definitely provide a productivity boost for many applications especially when compared to writing data access code from scratch.