# Saturday, October 25, 2008

LINQ to SQL external mapping file

With LINQ to SQL you can choose to use an external mapping file, allowing you to map SQL statements to CLR objects (also referred to as POCO, Plain Old CLR Objects). Doing so means you do not need to adorn your classes with attributes.
Here's a little sample of how to do this.

public class Supplier
{
    public int ID { get; set; }
    public string Name { get; set; }
}
 
public List<Supplier> GetSupplier( string name )
{
    SqlConnection conn = new SqlConnection( cConnectionString );
 
    XmlMappingSource xms = XmlMappingSource.FromUrl( @"mapping.xml" );
 
    var db = new DataContext( conn, xms );
 
    Table<Supplier> Suppliers = db.GetTable<Supplier>();
 
    var query = from s in Suppliers
                where s.Name == name
                select s;
 
    return query.ToList();
}
 
 

The XML can be as simple as:

<?xml version="1.0" encoding="utf-8"?>
<Database Name="VideoGameStoreDB"
          xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
  <Table Name="dbo.Supplier" Member="Supplier">
    <Type Name="Supplier">
      <Column Name="SupplierID" Member="ID" />
      <Column Name="SupplierName" Member="Name"  />
    </Type>
  </Table>
</Database>
 

You can use SQLMetal (a command line tool included with Visual Studio) to generate a mapping file.

#    Comments [0] |