Step 4. Load the XML Mapping File into the DataContext Object
Once the data entity class, XML mapping file and custom DataContext class have been created you can use the DataContext class to query the database and automatically map the appropriate database fields to their corresponding Model.Customer properties. When using the LINQ-to-SQL designer you can simply create a new instance of the DataContext class and be on your way since the designer generates code that includes C# or VB.NET mapping attributes. When using XML mapping files you'll need to load the mapping file into the DataContext object so that it knows the proper mappings to use. Here's an example of creating a CustomDataContext object instance and loading the XML mapping file. Notice that the mapping file is loaded by using System.Data.Linq.Mapping.XmlMappingSource class's FromUrl() method. XML mapping files can also be loaded from a string, stream, or XmlReader.
using System; using System.Collections.Generic; using System.Linq; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Text; namespace LINQAndXMLMapping { class Program { static void Main(string[] args) { string connStr = "server=.;database=AdventureWorksLT;integrated security=true;"; using (CustomDataContext context = new CustomDataContext(connStr, XmlMappingSource.FromUrl("CustomerMapping.xml"))) { //Perform query } Console.Read(); } } }