How can we use XML files to map LINQ attributes to simple .NET classes?

 Posted by ArticlesMaint on 9/29/2009 | Category: LINQ Interview questions | Views: 5934


LINQ had provided attribute based XML mapping. So you can have your pure .NET class like the ‘clsCustomer’ class shown below and you can define the LINQ mapping in a XML file. LINQ engine can then read the mapping from a XML file and apply the same to your simple .NET classes.

 


public class clsCustomer

{
private int _intCustomerId;
private string _strCustomerName;
private string _strCustomerCode;

public int CustomerId
{
set
{
_intCustomerId = value;
}
get
{
return _intCustomerId;
}
}
public string CustomerName
{
set
{
_strCustomerName = value;
}
get
{
return _strCustomerName;
}
}
public string CustomerCode
{
set
{
_strCustomerCode = value;
}
get
{
return _strCustomerCode;
}
}}


 


We need to then create a simple XML file which defines the mapping with the class members.
 

<?xml version="1.0" encoding="utf-8"?>

<Database Name="TstServer" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
<Table Name="dbo.Customer" Member="WebAppMappingXML.clsCustomer">
<Type Name="WebAppMappingXML.clsCustomer">
<Column Name="CustomerId" Member="CustomerId" />
<Column Name="CustomerName" Member="CustomerName" />
<Column Name="CustomerCode" Member="CustomerCode" />
</Type>
</Table>
</Database>


 


To bind the XML mapping with the simple .NET class we need to first create the XMLMappingSource object as shown in the below code snippet.
 

XmlMappingSource xms = XmlMappingSource.FromUrl(physicalPath + "Mapping.xml");


 


We need to pass the XMLMappingSource object to the datacontext class shown in the below code snippet.
 

DataContext objContext = new DataContext(strConn, xms);


 


Finally we can get the table and loop through the entity objects.
 

var query = from customer in objContext.GetTable<clsCustomer>()

select customer;

foreach (var item in query)
{
Response.Write(item.CustomerCode + "<br>");
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response