Você está na página 1de 13

Articles from Jinal Desai .

NET
LINQ Interview Questions
2011-10-22 00:10:11 Jinal Desai

What is LINQ? LINQ, or Language INtegrated Query, is a set of classes added to the .NET Framework 3.5. LINQ adds a rich, standardized query syntax to .NET programming languages that allows developers to interact with any type of data. What are the advantages of using LINQ or Language INtegrated Query? In any data driven application, you get data either from a Database, or an XML file or from collection classes. Prior to LINQ, working with each data source requires writing a different style of code. Moreover, working with external resources like data bases, XML files involves communicating with that external resource in some syntax specific to that resource. To retrieve data from a database you need to send it a string that contains the SQL query to execute, similarly, to work with an XML document involves specifying an XPath expression in the form of a string. The idea is that using LINQ you can work with disparate data sources using a similar style without having to know a separate syntax for communicating with the data source (e.g., SQL or XPath) and without having to resort to passing opaque strings to external resources. In any data driven web application or windows application, we use database as a datasource for the application. In order to get data from the database and display it in a web or windows application, we typically do the following. 1. Prepare your SQL Statements. 2. Execute SQL Statements against the database. 3. Retrieve the results. 4. Populate the Business Objects. 5. Display the Data in the Web Form or Windows From. public List<Customer> GetCustomerByCity(int CityId) { //Connection String = ""; string connStr = ""; //Prepare the connection object and connect to the database SqlConnection conn = new SqlConnection(connStr); //Open Connection conn.Oepn(); //Prepare Query string query = "SELECT * FROM Customers WHERE CityId = @CityId"; //Define command object with parameters SqlCommand comd = new SqlCommand(query, conn); comd.Parameters.AddWithValue("@CityId", CityId); //Get the DataReader SqlDataReader reader = comd.ExecuteReader(); //Populate list of customers List<Cuustomer> customersList = new List<Customer>(); While(reader.Read()) { Customer cust = new Customer(); cust.Id = reader["Id"].ToString(); cust.Name = reader["Name"].ToString(); customersList.Add(cust); } //Close Everything reader.Close(); conn.Close(); //Return customer list return customersList; } In order to send a query to the database we must first establish a connection to the database. We then must encode the logic the SQL query, its parameters, and the parameters values into strings that are supplied to the SqlCommand object. And because these inputs are encoded into opaque strings, there is no compile-time error checking and very limited debugging support. For example, if there is a spelling mistake in the SELECT query causing the Customets table name to be misspelled, this typographical error wont show up until runtime when this page is viewed in a web browser. These typographical errors

are easy to make as there is no IntelliSense support. When we use LINQ, Visual Studio would display an error message alerting us about the incorrect table name. Another mismatch between the programming language and the database is that the data returned by the database is transformed for us into objects accessible through the SqlDataReader, but these objects are not strongly-typed objects like wed like. To get this data into strongly-typed objects we must write code ourselves that enumerates the database results and populates each record into a corresponding object. LINQ was designed to address all these issues. LINQ also offers a unified syntax for working with data, be it data from a database, an XML file, or a collection of objects. With LINQ you dont need to know the intricacies of SQL, the ins and outs of XPath, or various ways to work with a collection of objects. All you need be familiar with is LINQs classes and the associated language enhancements centered around LINQ. In other words, LINQ provides type safety, IntelliSense support, compile-time error checking, and enhanced debugging scenarios when working with different datasources. What are the three main components of LINQ or Language INtegrated Query? 1. Standard Query Operators 2. Language Extensions 3. LINQ Providers How are Standard Query Operators implemented in LINQ? Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface. How are Standard Query Operators useful in LINQ? Standard Query Operators in LINQ can be used for working with collections for any of the following and more. 1. Get total count of elements in a collection. 2. Order the results of a collection. 3. Grouping. 4. Computing average. 5. Joining two collections based on matching keys. 6. Filter the results List the important language extensions made in C# to make LINQ a reality? 1. Implicitly Typed Variables 2. Anonymous Types 3. Object Initializers 4. Lambda Expressions What is the purpose of LINQ Providers in LINQ? LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source. What are the four LINQ Providers that .NET Framework ships? 1. LINQ to Objects Executes a LINQ query against a collection of objects 2. LINQ to XML Executes an XPATH query against XML documents 3. LINQ to SQL Executes LINQ queries against Microsoft SQL Server. 4. LINQ to DataSets Executes LINQ queries against ADO.NET DataSets. Write a program using LINQ to find the sum of first 5 prime numbers? Class Sample { static void Main() { int[] primeNum = {1, 2, 3, 5, 7}; //Use Count() and Sum() Standard Query Operators Console.WriteLine("The Sum of first {0} prime numbers is {1}", primeNum.Count(), primeNum.Sum()); } } What is Lambda Expression? A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as goes to operator. Left side of this operator specifies the input parameters and contains the expression or statement block at

the right side. Example: myExp = myExp/10; Now, let see how we can assign the above to a delegate and create an expression tree: delegate int myDel(int intMyNum); static void Main(string[] args) { //assign lambda expression to a delegate: myDel myDelegate = myExp => myExp / 10; int intRes = myDelegate(110); Console.WriteLine("Output {0}", intRes); Console.ReadLine(); //Create an expression tree type //This needs System.Linq.Expressions Expression<myDel> myExpDel = myExp => myExp /10; } Note: The => operator has the same precedence as assignment (=) and is right-associative. Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where. How LINQ is beneficial than Stored Procedure? There are couple of advantage of LINQ over stored procedures. 1. Debugging It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studios debugger to debug the queries. 2. Deployment With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy. 3. Type Safety LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception! Why Select Clause comes after From Clause in LINQ Query? The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So thats why from clause must appear before Select in LINQ. What is the extension of the file, when LINQ to SQL is used? The extension of the file is .dbml. What is the use of System.Data.DLinq.dll? System.Data.DLinq.dll provides functionality to work with LINQ to SQL. What is the use of System.XML.XLinq.dll? System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML. Which assembly represents the core LINQ API? System.Query.dll assembly represents the core LINQ API. What is the benefit of using LINQ on Dataset? The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset. Suppose we want to combine the results from two Datasets, or we want to take a distinct value from the Dataset, then it is advisable to use LINQ. Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not able to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and provides some new features as compared to ADO.NET. What is the disadvantage of LINQ over stored procedures? The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are precompiled. In case of LINQ the queries need to be compile before the execution. So according to this, I can say stored procedures are faster in performance as compared to LINQ. What are Quantifiers? They are LINQ Extension methods which return a Boolean value 1)All

2)Any 3)Contains 4)SequenceEqual example: int[] arr={10,20,30}; var b=arr.All(a=>a>20); Output: b will return False since all elements are not > 20. Difference between XElement and XDocument Both are the classes defined by System.Xml.Linq namespace XElement class represents an XML fragment XDocument class represents an entire XML document with all associated meta-data. example: XDocument d = new XDocument( new XComment("hello"), new XElement("book", new XElement("bookname", "ASP.NET"), new XElement("authorname", "techmedia") ); Briefly can you explain the purpose of LINQ providers in LINQ ? They are a set of classes that takes a LINQ query and dynamically generates a sql query which is executed against a specific data source(sql database, oracle, xml file, arrayetc) Why var keyword is used and when it is the only way to get query result? var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalised keyword. The compiler infers the actual type from the static type of the expression used to initialise the variable. One must use var with the query that returns anonymous type. E.g. // anonymous type returned var query = from w in words select new { LetterCount = w.Length, UpperString = w.ToUpper() }; foreach (var item in query) { Console.WriteLine(item.LetterCount + " " + item.UpperString); } What is Deffered Execution? Deferred execution means that the actual work will not be performed immediately, but rather when the result is requested at a latter stage. This is implemented via proxy pattern and perhaps yield return. The benefits of deferred executions are that potential heavy load on CPU, memory or database is delayed to the moment it is absolutely required, therefore saving time say while initialisation. Explain Query Expression syntax, Fluent syntax, Mixed Queries. Query expression syntax is based on the new keywords such as from, select, join, group by, order by etc. string[] words = { "roll", "removal", "fuse", "accusation", "capture", "poisoning", "accusation" }; var query = from w in words where w.Length > 4 orderby w ascending select w; This query selects words with more than 4 letters and presents result in the ascending order. Fluent syntax is based on the regular C# methods that are linked in a chain, like this sample from msdn. List<Customer> customers = GetCustomerList(); var customerOrders = customers .SelectMany(

(cust, custIndex) => cust .Orders .Select(o => "Customer #" + (custIndex + 1) + " has an order with OrderID " + o.OrderID)); Mixed syntax means query expression syntax is mixed with fluent method calls, for example it can be used to get the distinct values, first result or to get items as array (which by the way will trigger immediate query execution) What are Interpreted Queries? LINQ combines two architectural models: in-memory local and remote. The first one is basically LINQ-to-Objects and LINQ-to-XML. Local model closely work with IEnumerable<T> and decorator sequences of C# methods, lambdas and delegates. The query is compiled into standard imperative IL code. The second one is LINQ-to-SQL and LINQ-to-Entities. Remote model in contrast is rather declarative to the runtime. Sequences in query implement the IQueryable<T> (which in turn derives from IEnumerable<T>) and after the compilation resolve into query operators from Queryable class expression trees. Depending on the query provider, expression trees will be later interpreted by the runtime and are friendly to the remote data source. Use of IQueryable and IEnumerable interfaces. IEnumerable<T> is applicable for in-memory data querying, in contrast IQueryable<T> allows remote execution, like web service or database querying. Misuse of the interface can result in performance and memory problems, e.g. if IEnumerable<T> is used instead of IQueryable<T> to perform paging all the rows from data source will be loaded, instead of only those rows from the current page. Will there be any issues adding a table without primary keys to a data model? Every entity must have a key, even in the case where the entity maps to a view. When you use the Entity Designer to create or update a model, the classes that are generated inherit from EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add it to the data model. How do you truncate a table using entity data model? Unfortunately Entity Framework doesnt include anything straight forward to handle this. But we can still call a T-SQL statement using entity framework that will still minimizes the developers work. We can call ExecuteStoreCommand() methond on ObjectContext as shown below. using (var context = new MyTestDbEntities()) { context.ExecuteStoreCommand("TRUNCATE table Dummy"); } How do you query in entity model when the result has a join from from different database other than the entity model? E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1 As the entity model doesnt support querying from any entity other than the entities defined in Entity Data Model, we have to query aginst the data base using ExecuteStoredQuery of the context. Following code snippet shows how to query when other databases are joined. string query = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1"; using (var context = new SampleEntities()) { ObjectResult<DbDataRecord> records = context.ExecuteStoreQuery<DbDataRecord>(query); foreach (DbDataRecord record in records) { //Do whatever you want } } Can I use LINQ with databases other than SQL Server? Explain how. LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with other databases through LINQ to Objects or LINQ to Datasets, where the objects and datasets then take care of database specific operations and LINQ only needs to deal with those objects, not the database operations directly. How can we find Sequence of Items in two different array (same Type) in the same order using linq query? Public void MatchSequenceLinq() { Var wordsA = {"Rahul","ashok","sweta"}; Var wordsB = {"rahul","ashok","sweta"}; var match = wordsA.SequenceEqual(wordsB);

Console.WriteLine("The sequences match: {0}", match); } What is OfType in linq? public void TypeofExa() { Var numbers = {null,1.0,"two", 3,"four",5,"six",7.0 }; var doubles = from n in numbers where n is doublen; Console.WriteLine("Numbers stored as doubles:"); foreach (object d in doubles) { Console.WriteLine(d); } } Output: Numbers stored as doubles: 1 7 What is Lambda Expressions? How can we optimize our linq code using this Expression? Lambda expressions can be considered as a functional superset of anonymous methods, providing the following additional functionality: Lambda expressions can infer parameter types, allowing you to omit them. Lambda expressions can use both statement blocks and expressions as bodies, allowing for a terser syntax than anonymous methods, whose bodies can only be statement blocks. Lambda expressions can participate in type argument inference and method overload resolution when passed in as arguments. Note: anonymous methods can also participate in type argument inference (inferred return types). In C#, a lambda expression is written as a parameter list, followed by the => token,followed by an expression or a statement block. How can you find average of student marks from student tables (Columns are StudentID, Marks)? Public void LinqToSqlAverage() { var query = (from p in db. student. Marks).Average(); Console.WriteLine(q); } Write a Program for Concat to create one sequence of Data Rows that contains DataTabless Data Rows, one after the other. Public void Datasetlinq() { var numbersA = TestDS.Tables("NumbersA").AsEnumerable(); var numbersB = TestDS.Tables("NumbersB").AsEnumerable(); var allNumbers = numbersA.Concat(numbersB); Console.WriteLine("All numbers from both arrays:"); foreach (object n_loopVariable in allNumbers) { n = n_loopVariable; Console.WriteLine(n["number"]); } } Write a Program using Skip and Take operators. How can it beneficial for bulky data accessing on page? skip and take Operator used for Paging. Suppose we have Customer table of 100 records. To find 10 records by skipping the first 50 records from customer table. Public void Pagingdatasource () { Var Query =from CusDetails in db.customer skip (50) Take (10) ObjectDumper.Write(q) } Hence The LinQ SKIP operator lets you skip the results you want, and Take Operator enables you yo select the rest of result . So By Using Skip and Take Operator, You can create paging of Specific sequence. Write small Program to generate Xml Document from table like (StudentRecord Table) using linq

query. Public void CreateXmlDocFromArray() { // Now enumerate over the array to build an XElement. XElement StudentRecords = new XElement("StudentInfo", from c in Student select new XElement("Student", new XAttribute("Name", c.Name), new XElement("RollNo", c.RollNo) ) ); Console.WriteLine(StudentRecords); } What are the four language extensions in C# 3.0 useful for LINQ? a) Lambda ExpressionsA lambda expression is an anonymous function that can be used to create delegates. b) Anonymous TypesAnonymous types are used to create a set of read-only properties into a single object without defining a type first. c)Object InitializersObject Initializers is a new offering in C# 3.0 to create and initialize the objects in one step. d) Implicitly Typed Variables Can be assigned to any type.keyword used is var. What is the difference between OrderBy() and Sort() method over IList? OrderBy() sorts and gives the view IEnumerable(). But underlying list is sorted or not changed. Sort() modifies the underlying list. What is the difference between Select() and SelectMany()? Select() converts one type to another and returns enumerable. SelectMany() flattens the elements and gives a combined list of elements. What is the difference between Skip() and SkipWhile() extension methods? Skip() will take an integer argument and skips the top n numbers from the given IEnumerable. SkipWhile() continues to skip the elements as long as the input condition is true. Once condition turns false it will return all remaining elements. Is the method Where() using lambda expression returns values immediately? Nope. It is deferred execution. It will return an object which contains the information to execute the query. The actual filtering happens when the enumeration of elements starts. The enumeration could be started by using a foreach loop. Are Where() and TakeWhile() both having same functionalities? No. Where() will return all elements for given condition. Take() will return elements until given condtion is true. Once condition turned false it exits the iteration and remaining elemments are not checked. Which is the Lambda Expression enabled extension method to check any elements satisfies given condition? Any(). Which is the Lambda Expression enabled extension method to check all elements satisfies given condition? All(). How to find the index of element using Where() with Lambda Expressions? Use the two argumented Lambda method. Where((i, ix) => i == ix); 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. 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; 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}; Can we encapsulate the set and get properties for LINQ entities? [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; } } } 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 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; } } } 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 its a stored procedure and in case it is true that means its a user defined function. [Function(Name = "usp_SelectCustomer", IsComposable = false)] public ISingleResult<clsCustomerEntity> getCustomerAll() { } Step 5:- Invoke Executemethod call Ok now its 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); } 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. 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>"); } You are set with answers for LINQ Interview. Blog this! Bookmark on Delicious Digg this post Recommend on Facebook Share on FriendFeed Share on Linkedin Share on Orkut share via Reddit Share with Stumblers Share on technorati Tweet about it Subscribe to the comments on this post

Você também pode gostar