LINQ Exclusive Interview Questions and Answers (27) - Page 1

  • A joint initiative from DotNetFunda.Com and Questpond.
  • A one stop place on the internet to get trusted and proven Interview Questions (based on more than a decade of experience in this field) to ensure the success of the candidates.
  • You will find almost all Interview questions from Questpond here and this list is growing day by day with all latest and updated interview questions.

27 records found.

Get 650+ Questpond's Interview videos on discount

Define LINQ?

LINQ is a uniform programming model for any kind of data access. LINQ enables you to query and manipulate data independently of data sources. Below figure 'LINQ' shows how .NET language stands over LINQ programming model and works in a uniformed manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.
LINQ can serve as a good entity for middle tier. So it will sit in between the UI and data access layer.
 



Figure - LINQ


 


Below is a simple sample of LINQ. We have a collection of data ‘objcountries’ to which LINQ will is making a query with country name ‘India’. The collection ‘objcountries’ can be any data source dataset, datareader, XML etc. Below figure ‘LINQ code snippet’ shows how the ‘ObjCountries’ can be any can of data. We then query for the ‘CountryCode’ and loop through the same.



Figure: - LINQ code snippet


How does LINQ help us from the perspective of business objects?

One of the tedious jobs in business object is parsing and searching object collections. For instance consider the below figure where we want to search a country by an ‘ID’ value. So what we do is loop through the collection and get the object. Many may argue how about keeping a key in List or Array. The below example is just a sample. For instance if you want to search using country code and name, list / collection keys will not work with those multi-value searches.
 



In other words using LINQ we can query business object collections and filter the collection in a single LINQ query.
 


Can you explain how a basic LINQ Query looks like?

In order to understand the basic query for LINQ, let’s make a small sample project. Let’s take customer data which has customer and orders.
 




























Customer Name Customer Code City Orders
Khadak 001 Mumbai

  • Shirts

  • Socks
Shiv 002 Delhi

  • Pants
Raju 003 Mumbai

  • Socks
Shaam 004 Delhi

  • Shoes

We have made the data a bit complex by have one customer and multiple orders , in other words we have one as to many relationship.



So let’s make two classes one is the customer class aggregated with a collection of addresses class. Below is how the class structure will look like to accommodate the one as to many relationships of customer and multiple addresses.



The multiple addresses are the array collection aggregated inside the customer class. So below is the code snippet which is loading the customer and address collections with hard coded data provided in the above table. Currently its hardcoded but this can be loaded from database or some other source also.

clsCustomer[] objCustomer = new clsCustomer[]

{
new clsCustomer{CustomerName="Khadak",customerCode="001",City="Mumbai",Orders = new clsOrder[]
{new clsOrder{ProductName="Shirt"},
new clsOrder{ProductName="Socks"}}},
new clsCustomer{CustomerName="Shiv",customerCode="002",City="Delhi",Orders = new clsOrder[]{new clsOrder{ProductName="Pants"}}},
new clsCustomer{CustomerName="Raju",customerCode="003",City="Mumbai",Orders = new clsOrder[]{new clsOrder{ProductName="Socks"}}},
new clsCustomer{CustomerName="Shaam",customerCode="004",City="Delhi",Orders = new clsOrder[]{new clsOrder{ProductName="Shoes"}}}};

A basic LINQ query looks like something as shown below. Its start with the verb from followed by the data type and object i.e. ‘clsCustomer’ and ‘obj’ object. ‘objCustomer’ is the collection which has customer and addresses which we have loaded in the top section. ‘select obj’ specifies that we need all the values.
 

from clsCustomer obj in objCustomer select obj

Below figure shows in the right hand side the query in LINQ. In the left hand side we loop through the object collection.
 


  

We have made a simple project which demonstrates the basic LINQ query; you can download the same see how it works actually. Below figure shows the execution of the simple query.



How do we write a LINQ query to search with criteria?

We need to put the where clause before the ‘select’ keyword.
 

return from clsCustomer Obj in objCustomer where Obj.customerCode == “001” select Obj;

Below figure shows the where clause in action.
 



How can do a join using LINQ query?

Below is the LINQ code snippet for creating joins between object collections. In this case we are creating a join on customer and orders. If you remember the order collection was contained in the customer class.
 

return from clsCustomer ObjCust in objCustomer 

from clsOrder ObjOrder in ObjCust.Orders
select ObjCust;

Below is the result of how LINQ join query looks like.
 



How can we do a group by using LINQ query

Below is the code snippet which shows how group by query is written using LINQ. You can see we have created first a temp variable i.e. ‘GroupTemp’ and then we have used the ‘Select’ clause to return the same.
 

var GroupCustomers = from ObjCust in objCustomer

group ObjCust by ObjCust.City into GroupTemp
select new {GroupTemp.Key,GroupTemp};

Below image shows group by in action.
 



How can we do an order by using LINQ query?

Order by in LINQ is pretty simple. We just need to insert order by before the ‘Select’ query.
 

return from clsCustomer ObjCust in objCustomer

orderby ObjCust.City
select ObjCust;

Below figure shows how we have ordered on the city name.
 



Can you show a simple LINQ to SQL example?

So let’s first start with a simple LINQ to SQL example and then we will try to understand how we can establish relationship in LINQ entities.
 


Step 1:- Define Entity classes using LINQ
 


When we design project using tiered approach like 3-tier or N-tier we need to create business classes and objects. For instance below is a simple class which defines a class which is mapped to a country table as shown below. You can see we how the class properties are mapped in one to one fashion with the table. These types of classes are termed as entity classes.
 



In LINQ we need to first define these entity classes using attribute mappings. You need to import “System.Data.Linq.Mapping;” namespace to get attributes for mapping. Below is the code snippet which shows how the ‘Table’ attribute maps the class with the database table name ‘Customer’ and how ‘Column’ attributes helps mapping properties with table columns.
 

[Table(Name = "Customer")]

public class clsCustomerEntityWithProperties
{
private int _CustomerId;
private string _CustomerCode;
private string _CustomerName;

[Column(DbType = "nvarchar(50)")]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}

[Column(DbType = "nvarchar(50)")]
public string CustomerName
{
set
{
_CustomerName = value;
}
get
{
return _CustomerName;
}
}

[Column(DbType = "int", IsPrimaryKey = true)]
public int CustomerId
{
set
{
_CustomerId = value;
}
get
{
return _CustomerId;
}
}
}


 


Below is a more sophisticated pictorial view of the entity classes mapping with the customer table structure.
 



 


Step 2:- Use the datacontext to bind the table data with the entity objects.
 


The second step is use the data context object of LINQ to fill your entity objects. Datacontext acts like a mediator between database objects and your LINQ entity mapped classes.
 



So the first thing is to create the object of datacontext and create a active connection using the SQL connection string.



DataContext objContext = new DataContext(strConnectionString);


The second thing is to get the entity collection using the table data type. This is done using the ‘gettable’ function of the datacontext.



Table<clsCustomerEntity> objTable =
objContext.GetTable<clsCustomerEntity>();


Once we get all the data in table collection it’s time to browse through the table collection and display the record.

 

foreach (clsCustomerEntity objCustomer in objTable)

{
Response.Write(objCustomer.CustomerName + "<br>");
}

 



 


Can we encapsulate the set and get properties for LINQ entities?

You can define setter and getter functions which encapsulate the private properties.
 

[Table(Name = "Customer")]

public class clsCustomerEntityWithProperties
{
private int _CustomerId;
private string _CustomerCode;
private string _CustomerName;

[Column(DbType = "nvarchar(50)")]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}

[Column(DbType = "nvarchar(50)")]
public string CustomerName
{
set
{
_CustomerName = value;
}
get
{
return _CustomerName;
}
}

[Column(DbType = "int", IsPrimaryKey = true)]
public int CustomerId
{
set
{
_CustomerId = value;
}
get
{
return _CustomerId;
}
}
}


Can you explain how round trips happen in LINQ?

First let’s try to understand how LINQ queries actually work and then we will see how round trips happen. Let’s consider the below database design where we have 3 tables customer, addresses and phone. There is one-many relationship between customer and addresses, while there is one-one relationship between address table and phones.
 



 



 


We have created three entities as per the table design i.e. ‘ClsCustomerWithAddresses’,’ClsAddresses’ and ‘ClsPhone’. We have defined the relationships between them using ‘EntitySet’ and ‘EntityRef’.



 


To fill the entity objects with data from table is a 5 step process. As a first step the datacontext connection is created using the connection string, LINQ query is created and then we start browsing through customer, address and phones.



 


Analyzing the LINQ SQL round trips
 


Ok, now that we have analyzed that it takes 5 steps to execute a LINQ query. So let’s try to figure out on which step does the LINQ query actually fire SQL to the database. So what we will do is we will run the above LINQ code and analyze the same using SQL profiler.

Just so that we do not catch with lot of SQL Server noise we have only enabled RPC and SQL batch events.
 



Now when you run the query you will find the below things:-
• The execution of actual SQL takes place when the for each statement is iterated on the LINQ objects.
• The second very stunning thing you will notice is that for every entity separate query is fired to SQL Server. For instance for customer one query is fired and then separate queries for address and phones are fired to flourish the entity object. In other words lot of round trips.
 



How can we avoid the extra round trips?

We can instruct LINQ engine to load all the objects using ‘DataLoadOptions’. Below are the steps involved to enable ‘DataLoadOptions’.

The first step is to create the data context class.
 

DataContext objContext = new DataContext(strConnectionString);


 


Second step is to create the ‘DataLoadOption’ object.
 

DataLoadOptions objDataLoadOption = new DataLoadOptions();


 


Using the LoadWith method we need to define that we want to load customer with address in one SQL.



objDataLoadOption.LoadWith<clsCustomerWithAddresses>(clsCustomerWithAddresses => clsCustomerWithAddresses.Addresses);

 


Every address object has phone object , so we have also defined saying that the phone objects should be loaded for every address object in one SQL.
 

objDataLoadOption.LoadWith<clsAddresses>(clsAddresses => clsAddresses.Phone);


 


Whatever load option you have defined you need to set the same to the data context object using ‘LoadOptions’ property.
 

objContext.LoadOptions = objDataLoadOption;


 


Finally prepare you query.
 

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>()

select objCustomer;

 


Start looping through the objects.


foreach (clsCustomerWithAddresses objCustomer in MyQuery)
{

Response.Write(objCustomer.CustomerName + "<br>");

foreach (clsAddresses objAddress in objCustomer.Addresses)
{
Response.Write("===Address:- " + objAddress.Address1 + "<br>");
Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>");
Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>");
}
}


 


Below is the complete source code for the same.
 

DataContext objContext = new DataContext(strConnectionString);

DataLoadOptions objDataLoadOption = new DataLoadOptions();
objDataLoadOption.LoadWith<clsCustomerWithAddresses>(clsCustomerWithAddresses => clsCustomerWithAddresses.Addresses);
objDataLoadOption.LoadWith<clsAddresses>(clsAddresses => clsAddresses.Phone);
objContext.LoadOptions = objDataLoadOption;
var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>()
select objCustomer;

foreach (clsCustomerWithAddresses objCustomer in MyQuery)
{

Response.Write(objCustomer.CustomerName + "<br>");

foreach (clsAddresses objAddress in objCustomer.Addresses)
{
Response.Write("===Address:- " + objAddress.Address1 + "<br>");
Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>");
Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>");
}
}


 


Abracadabra…. Now if you run the code LINQ has executed only one SQL with proper joins as compared to 3 SQL for every object shown previously.
 



Can you explain LINQ In-memory commits and physical commits?

Entity objects forms the base of LINQ technologies. So when any data is submitted to database it goes through the LINQ objects. Database operations are done through ‘DataContext’ class. As said previously entities form the base of LINQ, so all the data is sent to these entities first and then its routed to the actual physical database. Due to this nature of working database commits is a two step process, the first step is in-memory and final step is physical commits.
In order to do in-memory operation ‘DataContext’ has provided ‘DeleteOnSubmit’ and ‘InsertOnSubmit’ methods. When we call these methods from the ‘DataContext’ class they add and update data in the entity objects memory. Please note these methods do not change / add new data in the actual database.
Once we are done with the in-memory operations and we want to send all the updates to the database for that we need to call ‘SubmitChanges()’ method. This method finally commits data in to the physical database.
 



 


So let’s consider a customer table (customerid, customercode and customername) and see how we can do the in-memory and physical commit operations.
 


How can we execute stored procedures using LINQ?

Step 1:- Create a stored procedure
 


Below is the stored procedure which we will be used to flourish LINQ objects.


 

Create PROCEDURE dbo.usp_SelectCustomer

AS
Select CustomerId,CustomerCode,CustomerName from Customer
RETURN

 


Step 2:- Create the LINQ Entity
 


The above stored procedure returns ‘CustomerId’,’CustomerCode’, and ‘CustomerName’ , so we need to prepare a LINQ entity as per the returning stored procedure data. 
 

[Table(Name = "Customer")]

public class clsCustomerEntity
{
private int _CustomerId;
private string _CustomerCode;
private string _CustomerName;

[Column(DbType = "nvarchar(50)")]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}

[Column(DbType = "nvarchar(50)")]
public string CustomerName
{
set
{
_CustomerName = value;
}
get
{
return _CustomerName;
}
}

[Column(DbType = "int", IsPrimaryKey = true)]
public int CustomerId
{
set
{
_CustomerId = value;
}
get
{
return _CustomerId;
}
}
}


 


Step 3 :- Inherit from DataContext class
 


In order to execute stored procedures LINQ has provided ‘ExecuteMethod’ call function which belongs to ‘DataContext’ class. This function returns ‘ISingleresult’ of an entity collection. The ‘ExecuteMethod’ call function is a protected function and can only be invoked through inheritance. Methods and functions from which we call our stored procedures normally forms our DAL. In other words the ‘ExecuteMethod’ should be a part of our DAL.

As said the function is purely protected you can only invoke the same by inheritance and not aggregation. I am really not sure why this compulsion is put by Microsoft , so in other words we need to create one more extra class which inherits from ‘DataContext’ and then put in the corresponding function calls for stored procedures. So below is the code snippet where we have inherited from ‘DataContext’ class and created a new DAL class called as ‘ClsMyContext’.
 

public class clsMyContext : DataContext

{}

 


Step 4:- Attribute using Function attribute
 


We have created ‘GetCustomerAll’ function which is attributed with ‘Function’ attribute from ‘System.Data.Linq.Mapping’ namespace. The ‘Function’ attribute has a name parameter which specifies the stored procedure name; currently the stored procedure is ‘usp_SelectCustomer’ as defined in the previous steps.

The ‘IsComposable’ parameter defines whether this method call is for stored procedure or UDF i.e. User defined function. If ‘IsComposable’ is false that means it’s a stored procedure and in case it is true that means it’s a user defined function.
 

[Function(Name = "usp_SelectCustomer", IsComposable = false)]


public ISingleResult<clsCustomerEntity> getCustomerAll()
{
}


 


Step 5:- Invoke Executemethod call
 


Ok now it’s time to fill in the empty function ‘GetCustomerAll’. Below is the code snippet of how to execute the ‘ExecuteMethod’ call. This invocation returns back ‘IExecuteResult’ object.
 

IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentMethod()));


 


The object returned from ‘IExecuteResult’ has ‘ReturnValue’ property from which we can get results collection of ‘ClsCustomerEntity’ type.
 

ISingleResult<clsCustomerEntity> objresults = (ISingleResult<clsCustomerEntity>) objResult.ReturnValue;


 


Below is the complete code snippet with the function.
 

[Function(Name = "usp_SelectCustomer", IsComposable = false)]

public ISingleResult<clsCustomerEntity> getCustomerAll()
{
IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentMethod()));

ISingleResult<clsCustomerEntity> objresults = (ISingleResult<clsCustomerEntity>) objResult.ReturnValue;
return objresults;
}


 


Step 6:- Finally we call the data context in client
 


So at the final step we just create the context object , call our function and loop through the object collection display data.
 

clsMyContext objContext = new clsMyContext(strConnectionString);

foreach(var row in objContext.getCustomerAll())
{
Response.Write(row.CustomerCode);
}

Can you show a simple CRUD example using LINQ?


Step 1 :- Create the entity customer class
 


So as a first step we create the entity of customer class as shown in the below code snippet.



[Table(Name = "Customer")]
public class clsCustomerEntity
{
private int _CustomerId;
private string _CustomerCode;
private string _CustomerName;

[Column(DbType = "nvarchar(50)")]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}

[Column(DbType = "nvarchar(50)")]
public string CustomerName
{
set
{
_CustomerName = value;
}
get
{
return _CustomerName;
}
}

[Column(DbType = "int", IsPrimaryKey = true,IsDbGenerated=true)]
public int CustomerId
{
set
{
_CustomerId = value;
}
get
{
return _CustomerId;
}
}
}


 


Step 2:- Create using LINQ
 


Create data context
 


So the first thing is to create a ‘datacontext’ object using the connection string.



DataContext objContext = new DataContext(strConnectionString);

 


Set the data for insert




Once you create the connection using the ‘DataContext’ object the next step is to create the customer entity object and set the data to the object property.



clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;

 


Do an in-memory update



We then do an in-memory update in entity objects itself using ‘InsertOnSubmit’ method.



objContext.GetTable<clsCustomerEntity>().InsertOnSubmit(objCustomerData);

 


Do the final physical commit
 


Finally we do a physical commit to the actual database. Please note until we do not call ‘SubmitChanges()’ data is not finally committed to the database.
 

objContext.SubmitChanges();


 


The final create LINQ code
 


Below is the final LINQ code put together.
 

DataContext objContext = new DataContext(strConnectionString);

clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.GetTable<clsCustomerEntity>().InsertOnSubmit(objCustomerData);
objContext.SubmitChanges();

 


Step 3:- Update using LINQ
 


So let’s take the next database operation i.e. update.
 


Create data context
 


As usual we first need to create a ‘datacontext’ object using the connection string as discussed in the create step.



DataContext objContext = new DataContext(strConnectionString);

 


Select the customer LINQ object which we want to update
 


Get the LINQ object using LINQ query which we want to update
 

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()

where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)
select objCustomer;

 


Finally set new values and update data to physical database
 


Do the updates and call ‘SubmitChanges()’ to do the final update.



clsCustomerEntity objCustomerData = (clsCustomerEntity)MyQuery.First<clsCustomerEntity>();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.SubmitChanges();

 


The final code of LINQ update
 


Below is how the final LINQ update query looks like.



DataContext objContext = new DataContext(strConnectionString);
var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()
where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)
select objCustomer;
clsCustomerEntity objCustomerData = (clsCustomerEntity)MyQuery.First<clsCustomerEntity>();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.SubmitChanges();


 


Step 4:- Delete using LINQ
 


Let’s take the next database operation delete.
DeleteOnSubmit

We will not be going through the previous steps like creating data context and selecting LINQ object , both of them are explained in the previous section. To delete the object from in-memory we need to call ‘DeleteOnSubmit()’ and to delete from final database we need use ‘SubmitChanges()’.



objContext.GetTable<clsCustomerEntity>().DeleteOnSubmit(objCustomerData);
objContext.SubmitChanges();


 


Step 5 :- Self explanatory LINQ select and read



Now on the final step selecting and reading the LINQ object by criteria. Below is the code snippet which shows how to fire the LINQ query and set the object value to the ASP.NET UI.



DataContext objContext = new DataContext(strConnectionString);

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()
where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)
select objCustomer;

clsCustomerEntity objCustomerData = (clsCustomerEntity)MyQuery.First<clsCustomerEntity>();
txtCustomerCode.Text = objCustomerData.CustomerCode;
txtCustomerName.Text = objCustomerData.CustomerName;



How can we handle concurrency in LINQ?

LINQ gives three ways by which we can handle concurrency conflicts. To handle concurrency conflicts we need to wrap the LINQ to SQL code in a ‘TRY’ block and catch the ‘ChangeConflictException’. We can then loop through the ‘ChangeConflicts’ collection to specify how we want the conflict to be resolved.
 

catch (ChangeConflictException ex)

{
foreach (ObjectChangeConflict objchangeconf in objContext.ChangeConflicts)
{
objchangeconf.Resolve(RefreshMode.OverwriteCurrentValues);
}
}

 


There are 3 ways provided by LINQ system to handle concurrency conflicts:-
• KeepCurrentValues :- When this option is specified and concurrency conflicts happen LINQ keeps call the LINQ entity object values as it is and does not push the new values from the database in to the LINQ object.
• OverwriteCurrentValues :- When this option is specified the current LINQ object data is replaced with the database values.
• KeepChanges :- This is the most weird option but can be helpful in some cases. When we talk about classes it can have many properties. So properties which are changed are kept as it is but the properties which are not changed are fetched from the database and replaced.

We need to use the ‘RefereshMode’ to specify which options we need as shown in the below code snippet.
 



What other features are provided by LINQ to fine tuning concurrency at field level?

One of the best options provided by LINQ concurrency system is control of concurrency behavior at field level. There are three options we can specify using the ‘UpdateCheck’ attribute: -

Never: - Do not use this field while checking concurrency conflicts.

Always: - This option specifies that always use this field to check concurrency conflicts.

WhenChanged :- Only when the member value has changed then use this field to detect concurrency conflicts.

Below is the code snippet which show how we can use the ‘UpdateCheck’ attribute to control property / field level concurrency options as specified above.
 

[Column(DbType = "nvarchar(50)",UpdateCheck=UpdateCheck.Never)]

public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}


What kind of error reporting options are provided by LINQ when concurrency conflict occurs?

LINQ concurrency system lets you specify how you want the conflicts to be reported. LINQ system has given 2 ways to report conflicts:-

ContinueOnConflict: - This option says to the LINQ engine that continue even if there are conflicts and finally return all conflicts at the end of the process.

FailOnFirstConflict: - This option says stop as soon as the first conflict occurs and return all the conflicts at that moment. In other words LINQ engine does not continue ahead executing the code.
 



Both these options can be provided as an input in ‘SubmitChanges’ method using the ‘ConflictMode’ enum. Below is the code snippet of how to specify conflict modes.
 

objContext.SubmitChanges(ConflictMode.ContinueOnConflict);


What are compiled queries?

LINQ has provided something called as compiled LINQ queries. In compiled LINQ queries the plan is cached in a static class. As we all know that static class is global cache. So LINQ uses the query plan from the static class object rather than building the preparing the query plan from scratch.
 



Figure: - LINQ Query Caching

In all there are 4 steps which need to be performed right from the time LINQ queries are built till they are fired. By using compiled LINQ queries the 4 steps are reduced to 2 steps.
 



Figure: - Query plan bypasses many steps
 


What are the different steps involved to write compiled LINQ queries?

The first thing is to import Data.Linq namespace.



Import namespace using System.Data.Linq;

 


The syntax to write compiled queries is a bit cryptic. So let us break those syntaxes in small pieces and then we will try to see how the complete syntax looks like. To execute a compiled function we need to write function to pointer. This function should be static so that LINQ engine can use the query plan stored in those static class objects.
Below is how we define the function it starts with ‘public static’ stating that this function is static. Then we use the ‘Func’ keyword to define the input parameters and output parameters. Below is how the parameter sequence needs to be defined:-
• The first parameter should be a data context. So we have defined the data type as ‘DataContext’.
• Followed by 1 or many input parameters currently we have only one i.e. customer code so we have defined the second parameter data type as string.
• Once we are done with all input parameters we need to define the data type of the output. Currently we have defined the output data type as ‘IQueryable’.
We have given a name to this delegate function as ‘getCustomers’.
 

public static Func<DataContext, string, IQueryable<clsCustomerEntity>> getCustomers


 


We need to call method ‘Compiled’ of static class ‘CompiledQuery’ with the datacontext object and necessary define input parameters followed by the LINQ query. For the below snippet we have not specified the LINQ query to minimize complications.



CompiledQuery.Compile((DataContext db, string strCustCode)=> Your LINQ Query );

 


So now uniting the above two code snippets below is how the complete code snippet looks like.
 

public static Func<DataContext, string, IQueryable<clsCustomerEntity>> getCustomers= CompiledQuery.Compile((DataContext db, string strCustCode)=> Your LINQ Query );


 


We then need to wrap this static function in a static class. So we have taken the above defined function and wrapped that function in a static class ‘clsCompiledQuery’.
 

public static class clsCompiledQuery

{
public static Func<DataContext, string, IQueryable<clsCustomerEntity>>
getCustomers = CompiledQuery.Compile((DataContext db, string strCustCode)
=> from objCustomer in db.GetTable<clsCustomerEntity>()
where objCustomer.CustomerCode == strCustCode
select objCustomer);

}


 


Consuming the compiled query is pretty simple; we just call the static function. Currently this function is returning data type as ‘IEnumerable’. So we have to define an ‘IEnumerable’ customer entity which will be flourished through the ‘getCustomers’ delegate function. We can loop through the customer entity using ‘clsCustomerEntity’ class.



IQueryable<clsCustomerEntity> objCustomers = clsCompiledQuery.getCustomers(objContext, txtCustomerCode.Text);
foreach (clsCustomerEntity objCustomer in objCustomers)
{
Response.Write(objCustomer.CustomerName + "<br>");
}


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

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>");
}


More LINQ Interview Questions & Answers here

Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Exclusive Interview Questions and Answers Categories