50
Define LINQ? Show/Hide Answer LINQ is a uniform programming model for any kind of data access. LINQ enables you to sources. Below figure 'LINQ' shows how .NET language stands over LINQ programming model data source. It’s like a query language which can query any data source and any transform time LINQ can serve as a good entity for middle tier. So it will sit in Figure - LINQ Below is a simple sample of LINQ. We have a collection of data ‘objcountries’ to which LIN ‘India’. The collection ‘objcountries’ can be any data source dataset, datareader, XML etc

LINQ

  • Upload
    abhi

  • View
    52

  • Download
    3

Embed Size (px)

Citation preview

Page 1: LINQ

Define LINQ?

Show/Hide Answer

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.

Page 2: LINQ

Figure: - LINQ code snippet

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

Show/Hide Answer

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. 

Page 3: LINQ

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?

Show/Hide Answer

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

Page 4: LINQ

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.

Page 5: LINQ

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.

Page 6: LINQ

 

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?

Page 7: LINQ

Show/Hide Answer

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?

Show/Hide Answer

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. 

Page 8: LINQ

How can we do a group by using LINQ query

Show/Hide Answer

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. 

Page 9: LINQ

How can we do an order by using LINQ query?

Show/Hide Answer

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. 

Page 10: LINQ

Can you show a simple LINQ to SQL example?

Show/Hide Answer

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. 

Page 11: LINQ

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;

Page 12: LINQ

[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)]

Page 13: LINQ

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. 

Page 14: LINQ

 

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.

Page 15: LINQ

 

foreach (clsCustomerEntity objCustomer in objTable)

{

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

}

 

 

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

Show/Hide Answer

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

{

Page 16: LINQ

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

{

Page 17: LINQ

_CustomerId = value;

}

get

{

return _CustomerId;

}

}

}

Can you explain how round trips happen in LINQ?

Show/Hide Answer

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. 

Page 18: LINQ

 

Page 19: LINQ

 

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’.

Page 20: LINQ

 

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.

Page 21: LINQ

 

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. 

Page 22: LINQ

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?

Show/Hide Answer

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();

Page 23: LINQ

 

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;

Page 24: LINQ

 

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)

{

Page 25: LINQ

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. 

Page 26: LINQ

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

Show/Hide Answer

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. 

Page 27: LINQ

How can we execute stored procedures using LINQ?

Show/Hide Answer

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;

Page 28: LINQ

[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)]

Page 29: LINQ

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

{}

 

Page 30: LINQ

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;

Page 31: LINQ

 

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

}

Page 32: LINQ

Can you show a simple CRUD example using LINQ?

Show/Hide Answer

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;

}

}

Page 33: LINQ

[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;

}

}

}

Page 34: LINQ

 

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

Page 35: LINQ

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();

 

Page 36: LINQ

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 

Page 37: LINQ

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 

Page 38: 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;

Page 39: LINQ

How can we handle concurrency in LINQ?

Show/Hide Answer

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. 

Page 40: LINQ

What is a Lambda expression?

Posted by: G_arora

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;

Page 41: LINQ

}

No te: 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.

What is LINQ?

Posted by: Virendradugar

It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET.

How LINQ is beneficial than Stored Procedures?

Posted by: Virendradugar

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 studio's 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?

Posted by: Virendradugar

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 that’s why from clause must appear before Select in LINQ.

What is the extension of the file, when LINQ to SQL is used?

Posted by: Virendradugar

The extension of the file is .dbml

What is the LINQ file extension that interacts with Code Behind's objects.

Posted by: Puneet20884

its .dbml

Why can't datareader by returned from a Web Service's Method

Posted by: Puneet20884

Page 42: LINQ

Cos, it's not serializable

What is the use of System.XML.XLinq.dll?

Posted by: Abhisek

System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.

What is the use of System.Data.DLinq.dll?

Posted by: Abhisek

System.Data.DLinq.dll provides functionality to work with LINQ to SQL.

Which assembly represents the core LINQ API?

Posted by: Abhisek

System.Query.dll assembly represents the core LINQ API.

Which class's extension methods are used in LINQ to SQL?

Posted by: Ddd

NOTE: This is objective type question, Please click question title for correct answer.

What is the benefit of using LINQ on Dataset?

Posted by: Tripati_tutu

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 are the advantages of LINQ over Stored Procedures?

Posted by: Tripati_tutu

Below is the three advantages of LINQ over stored procedures.

Debugging - As debug point concern, as LINQ is part of .NET, we can use the visual studio's debugger to debug the queries but it is tough to debug the Stored procedure as it will not support the visual studio debugger.

Deployment - In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will complie into single DLL hence deployment becomes easier.

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest to use LINQ because it helps to encounter an error at the compile time rather than at runtime exception.

What is the disadvantage of LINQ over stored procedures?

Page 43: LINQ

Posted by: Tripati_tutu

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?

Posted by: Ddd

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

Posted by: Ddd

Both are the classes defined by

XElement classrepresents 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"),

) );

When generating database mappings using LINQ to SQL, which tool allows you to create entity classes using a convenient graphical interface?

Posted by: Lokesh76

NOTE: This is objective type question, Please click question title for correct answer.

Briefly can you explain the purpose of LINQ providers in LINQ ?

Posted by: Akiii

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, array...etc) 

Page 44: LINQ

Thanks and RegardsAkiii

What is the difference between N-layer and N-tier architecture?

Posted by: Rambalak

N-layers of application may reside on the same physical computor(same tier) and the components in each layer communicates with the components of other layer by well defined interfaces.Layered architecture focuses on the grouping of related functionality within an application into distinct layers that are stacked vertically on top of each other.Communication between layers is explicit and loosely coupled.With strict layering, components in one layer can interact only with componentsin the same layer or with components from the layer directly below it.

The main benefits of the layered architectural style are:Abstraction,Isolation, Manageability, Performance, Reusability, Testability.

N-tiers architectue usually have atleast three separate logical parts,each located on separate physical server.Each tier is responsible with specific functionality.Each tier is completely independent from all other tier, except for those immediately above and below it.Communication between tiers is typically asynchronous in order to support better scalability.

The main benifit of tier achitecture styles are1.Maintainability. Because each tier is independent of the other tiers, updates or changes can be carried out without affecting the application as a whole.2.Scalability. Because tiers are based on the deployment of layers, scaling out an application is reasonably straightforward.3.Flexibility. Because each tier can be managed or scaled independently, flexibility is increased.4.Availability. Applications can exploit the modular architecture of enabling systems using easily scalable components, which increases availability.

Tell me the exact difference between IQueryable and IEnumerable interface ?

Posted by: Akiii

IEnumerable<T> is applicable for in-memory data querying, and in contrast IQueryable<T> allows remote execution, like web service or database querying.