DCSIMG
Linq to SQL Xml Based Mapping - Guy Burstein's Blog

Guy Burstein's Blog

Developer Evangelist @ Microsoft

News

Guy Burstein The Bu

Disclaimer
Postings are provided 'As Is' with no warranties and confer no rights.

Guy Burstein LinkedIn Profile

TwitterCounter for @bursteg

Links

Articles

Blogs I Read

Linq to SQL Xml Based Mapping

Linq to SQL Xml Based Mapping In the last post I talked about Linq to SQL Attribute Based Mapping that lets you map CLR Objects to database objects using attributes. Although this approach is very simple and easy, it is compiled with the code and cannot be changed without recompiling. Another approach is Linq to SQL Xml Based Mapping that maps entities to database objects according to an xml file that is loaded in runtime.

So, given the two entities from the previous post, that have no mapping attributes at all:

class Order

{

    public int Id { get; set; }

 

    public DateTime? OrderDate { get; set; }

 

    public string CustomerId { get; set; }

 

    private EntityRef<Customer> _customerRef;

    public Customer Customer

    {

        get { return this._customerRef.Entity; }

        set { this._customerRef.Entity = value; }

    }

}

and:

public class Customer

{

    public string CustomerId { get; set; }

}

The Xml Based Mapping schema should look like:

<Database Name="Northwind"

          xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">

 

  <Table Name="dbo.Customers" Member="Customers">

    <Type Name="XmlBasedMapping.Customer">

      <Column Name="CustomerID"

              Member="CustomerId"

              CanBeNull="false"

              IsPrimaryKey="true" />

    </Type>

  </Table>

 

  <Table Name="dbo.Orders" Member="Orders">

    <Type Name="XmlBasedMapping.Order">

      <Column Name="OrderID"

              Member="Id" IsPrimaryKey="true" IsDbGenerated="true" />

      <Column Name="CustomerID"

              Member="CustomerId" DbType="NChar(5)" />

      <Column Name="OrderDate"

              Member="OrderDate" DbType="DateTime" />

      <Association Name="Orders_Customers"

                  Member="Customers"

                  ThisKey="CustomerId"

                  OtherKey="CustomerId"

                  IsForeignKey="true" />

    </Type>

  </Table>

</Database>

The root element is the Database element. The child elements are the database objects the are included in the mapping - Customers and Orders tables from the Northwind database. Each table can have child types that are mapped to entities in the application. This hierarchy sits also with the concept of inheritance in Linq to SQL since it only supports the Table per Class Hierarchy strategy. In the above example each table is mapped to a single entity. Notice that each table column is mapped to a member in the class.

To work with this mapping source, we should load it from a file / stream / url or any other resource, and supply it as a parameter for the DataContext instance we want to work with.

string connectionString = "...";

 

// Load the Mapping from a file

XmlMappingSource mapping = XmlMappingSource.FromUrl("NorthwindMap.xml");

 

// Create a DataContext to the database, and supply

// the url for the mapping file

DataContext ctx = new DataContext(connectionString, mapping);

 

var query = from order in ctx.GetTable<Order>()

            where order.CustomerId == "ALFKI"

            select order;

foreach (Order order in query)

{

    Console.WriteLine(order.Id + " " + order.OrderDate + " " + order.CustomerId);

}

Enjoy!

Comments

TrackBack said:

# September 28, 2007 2:43 PM

TrackBack said:

# September 28, 2007 2:44 PM

Guy Burstein's Blog said:

Linq to SQL Inheritance If you read my post How To: Model Inheritance in Databases you&#39;d be familiar

# October 1, 2007 3:14 PM

Guy Burstein [MVP] said:

Linq to SQL Stored Procedures Continuing my Linq to SQL post series, this post talks about using Linq

# October 5, 2007 2:27 PM

Guy Burstein [MVP] said:

Linq to SQL Stored Procedures with Multiple Results - IMultipleResults Continuing my post series about

# October 5, 2007 9:10 PM

代震军 said:

最近有点空闲时间,抽空看了一下LINQ方面的东西。好在园子里这方面的系列文章很多. 免去了不少查找的时间. 因为本人习惯于学完就动手尝试,而我们的产品中也都将访问数据库的SQL语句统一封装进了DLL.所以就想先拿产品练一下手:)

# May 12, 2008 6:03 AM

代震军 said:

最近有点空闲时间,抽空看了一下LINQ方面的东西。好在园子里这方面的系列文章很多. 免去了不少查找的时间. 因为本人习惯于学完就动手尝试,而我们的产品中也都将访问数据库的SQL语句统一封装进了DLL.所以就想先拿产品练一下手:)

# May 12, 2008 6:07 AM

9who said:

没看懂

# July 28, 2008 3:19 AM

Michael said:

So if your table in the db changed you also have to update the code of entities, is there any work around not need to update the code of entities and compile your project when your db changed just the replace the map file?

# July 28, 2008 9:53 AM

Community Blogs said:

SharePoint Create your own customized usage report solution step by step SharePoint WebPart Property

# May 15, 2009 2:09 PM

Gunnar said:

Thanks for sharing! I wanted to ask if it is possible to avoid keeping parent object ID in child object? I mean if I have Product and ProductCategory classes and XML mapping then I don't want to keep ProductCategoryId in Product class. Is it somehow possible to achieve?

# June 11, 2009 3:27 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: