technology digestified - linq interview questions

Upload: techdigest

Post on 07-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    1/13

    Articles of Technology Digestified

    LINQ Interview Questions2011-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 arich, standardized query syntax to .NET programming languages that allows developers to interact withany 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 collectionclasses. 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 externalresource in some syntax specific to that resource. To retrieve data from a database you need to send it astring that contains the SQL query to execute, similarly, to work with an XML document involves specifyingan XPath expression in the form of a string. The idea is that using LINQ you can work with disparate datasources using a similar style without having to know a separate syntax for communicating with the datasource (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 theapplication. In order to get data from the database and display it in a web or windows application, wetypically 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 GetCustomerByCity(int CityId){//Connection String = "";string connStr = "";

    //Prepare the connection object and connect to the databaseSqlConnection conn = new SqlConnection(connStr);

    //Open Connectionconn.Oepn();

    //Prepare Querystring query = "SELECT * FROM Customers WHERE CityId = @CityId";

    //Define command object with parametersSqlCommand comd = new SqlCommand(query, conn);comd.Parameters.AddWithValue("@CityId", CityId);

    //Get the DataReaderSqlDataReader reader = comd.ExecuteReader();

    //Populate list of customersList customersList = new List();

    While(reader.Read()){Customer cust = new Customer();cust.Id = reader["Id"].ToString();cust.Name = reader["Name"].ToString();customersList.Add(cust);

    }

    //Close Everythingreader.Close();conn.Close();

    //Return customer listreturn customersList;

    }

    In order to send a query to the database we must first establish a connection to the database. We thenmust encode the logic the SQL query, its parameters, and the parameters values into strings that aresupplied to the SqlCommand object. And because these inputs are encoded into opaque strings, there isno compile-time error checking and very limited debugging support. For example, if there is a spellingmistake in the SELECT query causing the Customets table name to be misspelled, this typographicalerror wont show up until runtime when this page is viewed in a web browser. These typographical errors

    http://jinaldesai.net/http://jinaldesai.net/http://jinaldesai.net/linq-interview-questions/http://jinaldesai.net/
  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    2/13

    are easy to make as there is no IntelliSense support. When we use LINQ, Visual Studio would display anerror message alerting us about the incorrect table name.

    Another mismatch between the programming language and the database is that the data returned by thedatabase is transformed for us into objects accessible through the SqlDataReader, but these objects arenot strongly-typed objects like wed like. To get this data into strongly-typed objects we must write codeourselves 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, beit data from a database, an XML file, or a collection of objects. With LINQ you dont need to know theintricacies of SQL, the ins and outs of XPath, or various ways to work with a collection of objects. All youneed be familiar with is LINQs classes and the associated language enhancements centered aroundLINQ.

    In other words, LINQ provides type safety, IntelliSense support, compile-time error checking, andenhanced debugging scenarios when working with different datasources.

    What are the three main components of LINQ or Language INtegrated Query?

    1. Standard Query Operators2. Language Extensions3. LINQ Providers

    How are Standard Query Operators implemented in LINQ?Standard Query Operators are implemented as extension methods in .NET Framework. These StandardQuery Operators can be used to work with any collection of objects that implements the IEnumerableinterface. 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 collectionclasses 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 andmore.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 Variables2. Anonymous Types3. Object Initializers4. 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 thatexecutes 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 objects2. 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 OperatorsConsole.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. Lambdaexpression 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

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    3/13

    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.ExpressionsExpression 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 methodssuch 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 canuse visual studios debugger to debug the queries.

    2. Deployment With stored procedures, we need to provide an additional script for stored proceduresbut 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 toencounter 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 tobe declared first. From clause of LINQ query just defines the range or conditions to select records. Sothats 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 theDataset, 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 notable to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NETfunctionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and providessome 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, Ican 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

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    4/13

    2)Any3)Contains4)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 fragmentXDocument 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 isexecuted 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 generalisedkeyword. The compiler infers the actual type from the static type of the expression used to initialise thevariable. One must use var with the query that returns anonymous type. E.g.

    // anonymous type returnedvar 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 theresult is requested at a latter stage. This is implemented via proxy pattern and perhaps yield return. Thebenefits 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 wordswhere w.Length > 4orderby w ascendingselect w;

    This query selects words with more than 4 letters and presents

    result in the ascending order. Fluent syntax is based on the regularC# methods that are linked in a chain, like this sample from msdn.

    List customers = GetCustomerList();

    var customerOrders = customers.SelectMany(

    http://msdn.microsoft.com/en-us/vcsharp/aa336758#SelectTransformation
  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    5/13

    (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 beused to get the distinct values, first result or to get items as array (which by the way will trigger immediatequery 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 withIEnumerable and decoratorsequences of C# methods, lambdas and delegates. The query iscompiled into standard imperative IL code.

    The second one is LINQ-to-SQL and LINQ-to-Entities . Remote model in contrast is rather declarative tothe runtime. Sequences in query implement the IQueryable (which in turn derives fromIEnumerable) 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 theruntime and are friendly to the remote data source.

    Use of IQueryable and IEnumerable interfaces.

    IEnumerable is applicable for in-memory data querying, in contrast IQueryable allows remote

    execution, like web service or database querying. Misuse of the interface can result in performance andmemory problems, e.g. ifIEnumerable is used instead ofIQueryable to perform paging all therows 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 EntityDesigner to create or update a model, the classes that are generated inherit from EntityObject, whichrequires 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 stillcall a T-SQL statement using entity framework that will still minimizes the developers work. We can callExecuteStoreCommand() 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 otherthan 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 DataModel, 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 records = context.ExecuteStoreQuery(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 databasesthrough LINQ to Objects or LINQ to Datasets, where the objects and datasets then take care of databasespecific 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);

    http://www.dofactory.com/Patterns/PatternDecorator.aspx
  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    6/13

    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:17

    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 thefollowing 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 tersersyntax than anonymous methods, whose bodies can only be statement blocks.

    Lambda expressions can participate in type argument inference andmethod overload resolution when passed in as arguments. Note: anonymous methods can alsoparticipate in type argument inference (inferred return types).

    In C#, a lambda expression is written as a parameter list, followed by the => token,followed by anexpression 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 DataTablessData 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 onpage?

    skip and take Operator used for Paging. Suppose we have Customer table of 100 records. To find 10records 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 yoselect the rest of result . So By Using Skip and Take Operator, You can create paging of Specificsequence.

    Write small Program to generate Xml Document from table like (StudentRecord Table) using linq

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    7/13

    query.

    Public void CreateXmlDocFromArray(){

    // Now enumerate over the array to build an XElement.XElement StudentRecords = new XElement("StudentInfo",

    from c in Studentselect 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 createdelegates.b) Anonymous TypesAnonymous types are used to create a set of read-only properties into a singleobject without defining a type first.c)Object InitializersObject Initializers is a new offering in C# 3.0 to create and initialize the objects in onestep.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 andgives 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 willreturn 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 startedby 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 istrue. 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 satisfiesgiven condition?

    Any().

    Which is the Lambda Expression enabled extension method to check all elements satisfies givencondition?

    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 instanceconsider the below figure where we want to search a country by an ID value. So what we do is loopthrough the collection and get the object. Many may argue how about keeping a key in List or Array. Thebelow 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.

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    8/13

    In other words using LINQ we can query business object collections and filter the collection in a singleLINQ 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 creatinga join on customer and orders. If you remember the order collection was contained in the customer class.

    return from clsCustomer ObjCust in objCustomerfrom clsOrder ObjOrder in ObjCust.Ordersselect 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 havecreated first a temp variable i.e. GroupTemp and then we have used the Select clause to return thesame.

    var GroupCustomers = from ObjCust in objCustomergroup ObjCust by ObjCust.City into GroupTempselect 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;

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    9/13

    }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_SelectCustomerASSelect CustomerId,CustomerCode,CustomerName from CustomerRETURN

    Step 2:- Create the LINQ Entity

    The above stored procedure returns CustomerId,CustomerCode, and CustomerName , so we need toprepare 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 toDataContext class. This function returns ISingleresult of an entity collection. The ExecuteMethod callfunction is a protected function and can only be invoked through inheritance. Methods and functions fromwhich we call our stored procedures normally forms our DAL. In other words the ExecuteMethod shouldbe a part of our DAL.

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    10/13

    As said the function is purely protected you can only invoke the same by inheritance and not aggregation. Iam really not sure why this compulsion is put by Microsoft , so in other words we need to create one moreextra class which inherits from DataContext and then put in the corresponding function calls for storedprocedures. So below is the code snippet where we have inherited from DataContext class and createda 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 specifiesthe stored procedure name; currently the stored procedure is usp_SelectCustomer as defined in theprevious steps.

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

    [Function(Name = "usp_SelectCustomer", IsComposable = false)]public ISingleResult 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 executethe 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 resultscollection of ClsCustomerEntity type.

    ISingleResult objresults =(ISingleResult) objResult.ReturnValue;

    Below is the complete code snippet with the function.

    [Function(Name = "usp_SelectCustomer", IsComposable = false)]public ISingleResult getCustomerAll(){

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

    ISingleResult objresults =(ISingleResult) 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 objectcollection 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 conflictswe need to wrap the LINQ to SQL code in a TRY block and catch the ChangeConflictException. We canthen loop through the ChangeConflicts collection to specify how we want the conflict to be resolved.

    catch (ChangeConflictException ex){

    foreach (ObjectChangeConflict objchangeconf inobjContext.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

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    11/13

    the LINQ entity object values as it is and does not push the new values from the database in to the LINQobject. OverwriteCurrentValues :- When this option is specified the current LINQ object data is replaced withthe database values. KeepChanges :- This is the most weird option but can be helpful in some cases. When we talk aboutclasses it can have many properties. So properties which are changed are kept as it is but the propertieswhich 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 fieldlevel. 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 concurrencyconflicts.

    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 hasgiven 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 conflictsat 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 ConflictModeenum. 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 iscached in a static class. As we all know that static class is global cache. So LINQ uses the query planfrom 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.

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    12/13

    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 andthen we will try to see how the complete syntax looks like. To execute a compiled function we need towrite function to pointer. This function should be static so that LINQ engine can use the query plan storedin those static class objects.Below is how we define the function it starts with public static stating that this function is static. Then weuse the Func keyword to define the input parameters and output parameters. Below is how theparameter 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 wehave defined the output data type as IQueryable.We have given a name to this delegate function as getCustomers.

    public static Func getCustomers

    We need to call method Compiled of static class CompiledQuery with the datacontext object andnecessary define input parameters followed by the LINQ query. For the below snippet we have notspecified 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 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 functionand wrapped that function in a static class clsCompiledQuery.

    public static class clsCompiledQuery{

    public static Func getCustomers =CompiledQuery.Compile((DataContext db,

    string strCustCode)=> from objCustomer in db.GetTable()

    where objCustomer.CustomerCode == strCustCode

    select objCustomer);}

    Consuming the compiled query is pretty simple; we just call the static function. Currently this function isreturning data type as IEnumerable. So we have to define an IEnumerable customer entity which will beflourished through the getCustomers delegate function. We can loop through the customer entity usingclsCustomerEntity class.

  • 8/3/2019 Technology Digestified - LINQ Interview Questions

    13/13

    IQueryable objCustomers =clsCompiledQuery.getCustomers(objContext, txtCustomerCode.Text);foreach (clsCustomerEntity objCustomer in objCustomers){

    Response.Write(objCustomer.CustomerName + "
    ");}

    You are set with answers for LINQ Interview.

    Blog this!

    Bookmark on Delicious

    Digg this post

    Recommend on Facebook

    Share on FriendFeed

    Buzz it up

    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

    http://jinaldesai.net/linq-interview-questions/feedhttp://twitter.com/home/?status=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2Fhttp://technorati.com/faves?add=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2Fhttp://www.stumbleupon.com/submit?url=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&title=LINQ+Interview+Questionshttp://www.reddit.com/submit?url=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&title=LINQ+Interview+Questionshttp://promote.orkut.com/preview?nt=orkut.com&du=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&tt=LINQ+Interview+Questionshttp://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&title=LINQ+Interview+Questions&&summary=What+is+LINQ%3F+%0D%0A%0D%0ALINQ%2C+or+Language+INtegrated+Query%2C+is+a+set+of+classes+added+to+the+.NET+Framework+3.5.+LINQ+adds+a+rich%2C+standardized+query+syntax+to+.NET+programming+languages+that+allows+developers+to+interact+with+any+type+of+data.%0D%0A%0D%0AWhat+are+the+advantages+of+using+LINQ+or+Language+INtegrated+Query%3F%0D%0A%0D%0AIn+any+http://www.google.com/buzz/post?url=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&title=LINQ+Interview+Questionshttp://www.friendfeed.com/share?title=LINQ+Interview+Questions&link=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2Fhttp://www.facebook.com/sharer.php?u=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&t=LINQ+Interview+Questionshttp://digg.com/submit?url=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&title=LINQ+Interview+Questions&bodytext=What+is+LINQ%3F+%0D%0A%0D%0ALINQ%2C+or+Language+INtegrated+Query%2C+is+a+set+of+classes+added+to+the+.NET+Framework+3.5.+LINQ+adds+a+rich%2C+standardized+query+syntax+to+.NET+programming+languages+that+allows+developers+to+interact+with+any+type+of+data.%0D%0A%0D%0AWhat+are+the+advantages+of+using+LINQ+or+Language+INtegrated+Query%3F%0D%0A%0D%0AIn+any+http://delicious.com/post?url=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&title=LINQ+Interview+Questionshttp://www.blogger.com/blog_this.pyra?t&u=http%3A%2F%2Fjinaldesai.net%2Flinq-interview-questions%2F&n=LINQ+Interview+Questions&pli=1