You are on page 1of 45

Define LINQ?

Show/Hide Answer

LINQ is a uniform programming model for any kind of data access. LINQ enables you to query and manipul shows how .NET language stands over LINQ programming model and works in a uniformed manner over a query any data source and any transform. LINQ also provides full 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 LINQ will is making a objcountries can be any data source dataset, datareader, XML etc. Below figure LINQ code snippet shows query for the CountryCode and loop through the same.

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 ID value. So what we do is loop through the collection and get the object. Many may argue how about kee sample. For instance if you want to search using country code and name, list / collection keys will not work

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

Can you explain how a basic LINQ Query looks like?


Show/Hide Answer

In order to understand the basic query for LINQ, lets make a small sample project. Lets take customer dat

Customer Name Khadak

Customer Code 001

City Mumbai

Orders

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

So lets make two classes one is the customer class aggregated with a collection of addresses class. Below one as to many relationships of customer and multiple addresses.

The multiple addresses are the array collection aggregated inside the customer class. So below is the code collections with hard coded data provided in the above table. Currently its hardcoded but this can be loaded
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 clsO

new clsCustomer{CustomerName="Raju",customerCode="003",City="Mumbai",Orders = new clsOrder[]{new cls

new clsCustomer{CustomerName="Shaam",customerCode="004",City="Delhi",Orders = new clsOrder[]{new cls

A basic LINQ query looks like something as shown below. Its start with the verb from followed by the data objCustomer is the collection which has customer and addresses which we have loaded in the top section.

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 obje

We have made a simple project which demonstrates the basic LINQ query; you can download the same see the simple query.

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


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 collection was contained in the customer class.

return from clsCustomer ObjCust in objCustomer from clsOrder ObjOrder in ObjCust.Orders select ObjCust;

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

How can we do a group by using LINQ query


Show/Hide Answer

Below is the code snippet which shows how group by query is written using LINQ. You can see we have cre have used the Select clause to return the same.

var GroupCustomers = from ObjCust in objCustomer group ObjCust by ObjCust.City into GroupTemp select new {GroupTemp.Key,GroupTemp};

Below image shows group by in action.

How can we do an order by using LINQ query?


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.

Can you show a simple LINQ to SQL example?


Show/Hide Answer

So lets first start with a simple LINQ to SQL example and then we will try to understand

Step

1:-

Define

Entity

cl

When we design project using tiered approach like 3-tier or N-tier we need to create business classes and o class which is mapped to a country table as shown below. You can see we how the class properties are m classes are termed as

In LINQ we need to first define these entity classes using attribute mappings. You need to import Sy mapping. Below is the code snippet which shows how the Table attribute maps the class with the databas mapping properties with

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

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

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

[Column(DbType = "int", IsPrimaryKey = true)] public int CustomerId

{ set { _CustomerId = value; } get { return _CustomerId; } } }

Below

is

more

sophisticated

pictorial

view

of

the

entity

classes

ma

Step

2:-

Use

the

datacontext

to

bind

the

table

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

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

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 fu

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

Once

we

get

all

the

data

in

table

collection

its

time

to

browse

through

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

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

[Column(DbType = "nvarchar(50)")] public string CustomerCode { set {

_CustomerCode = value; } get { return _CustomerCode; } }

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

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

{ return _CustomerId; } } }

Can you explain how round trips happen in LINQ?


Show/Hide Answer

First lets try to understand how LINQ queries actually work and then we will see how round trips happen. tables customer, addresses and phone. There is one-many relationship between customer and addresses, and

We have created three entities as per the table design i.e. ClsCustomerWithAddresses,ClsAddresses a them using EntitySet and EntityRef.

To fill the entity objects with data from table is a 5 step process. As a first step the datacontext connec

created and then we start browsing through customer, address and phones.

Analyzing

the

LINQ

SQL

Ok, now that we have analyzed that it takes 5 steps to execute a LINQ query. So lets try to figure out o database. So what we will do is we will run the above LINQ code Just so that we do not catch with lot of SQL Server noise we have

Now when you run the query you will The execution of actual SQL takes place when the for each stat The second very stunning thing you will notice is that for every entity separate query is fired to SQL Se separate queries for address and phones are fired to flourish the entity o

How can we avoid the extra round trips?


Show/Hide Answer

We The

can

instruct

LINQ

engine

to step

load

all

the is

objects

using to

DataLoadOptions. create

Below

ar

first

the

DataContext objContext = new DataContext(strConnectionString);

Second

step

is

to

create

th

DataLoadOptions objDataLoadOption = new DataLoadOptions();

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

objDataLoadOption.LoadWith<clsCustomerWithAddresses>(clsCustomerWithAddresses => clsCustom

Every address object has phone object , so we have also defined saying that the phone objects s

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

Whatever

load

option

you

have

defined

you

need

to

set

the

same

to

the

objContext.LoadOptions = objDataLoadOption;

Finally

prepare

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

Start foreach {

looping (clsCustomerWithAddresses

through objCustomer + objAddress " " " + + +

Response.Write(objCustomer.CustomerName foreach (clsAddresses { Response.Write("===Address:Response.Write("========Mobile:Response.Write("========LandLine:} }

objAddress. objAddress.Phon objAddress.P

Below

is

the

complete

source

cod

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

foreach (clsCustomerWithAddresses objCustomer in MyQuery) {

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

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

Abracadabra. Now if you run the code LINQ has executed only one SQL with proper joins as c

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 DataContext class. As said previously entities form the base of LINQ, so all the data is sent to th database. Due to this nature of working database commits is a two step process, the first s In order to do in-memory operation DataContext has provided DeleteOnSubmit and InsertOnSubmit me class they add and update data in the entity objects memory. Please note these methods do Once we are done with the in-memory operations and we want to send all the updates to the database method finally commits data in to

So lets consider a customer table (customerid, customercode and customername) and see how we

How can we execute stored procedures using LINQ?


Show/Hide Answer

Step

1:-

Create

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

The above stored procedure returns CustomerId,CustomerCode, and CustomerName , so we need to p data.

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

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

return _CustomerCode; } }

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

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

} }

Step

:-

Inherit

from

In order to execute stored procedures LINQ has provided ExecuteMethod call function which belongs to D entity collection. The ExecuteMethod call function is a protected function and can only be invoked through stored procedures normally forms our DAL. In other words the ExecuteM

As said the function is purely protected you can only invoke the same by inheritance and not aggregation. , so in other words we need to create one more extra class which inherits from DataContext and then pu So below is the code snippet where we have inherited from DataContext class and c

public class clsMyContext : DataContext {}

Step

4:-

Attribute

using

We have created GetCustomerAll function which is attributed with Function attribute from System.Dat name parameter which specifies the stored procedure name; currently the stored procedure is

The IsComposable parameter defines whether this method call is for stored procedure or UDF i.e. User d stored procedure and in case it is true that means

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

public ISingleResult<clsCustomerEntity> getCustomerAll() {

Step

5:-

Invoke

Ok now its time to fill in the empty function GetCustomerAll. Below is the code snippet of how to exec IExecuteResult

IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentM

The

object

returned

from

IExecuteResult

has

ReturnValue

property

from

which

we

can

ISingleResult<clsCustomerEntity> objresults = (ISingleResult<clsCustomerEntity>) objResult

Below

is

the

complete

code

snippet

[Function(Name = "usp_SelectCustomer", IsComposable = false)] public ISingleResult<clsCustomerEntity> getCustomerAll() { IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentM

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

Step

6:-

Finally

we

call

the

So

at

the

final

step

we

just

create

the

context

object

call

our

function

and

clsMyContext objContext = new clsMyContext(strConnectionString); foreach(var row in objContext.getCustomerAll()) { Response.Write(row.CustomerCode); }

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

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

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

Step

2:-

Create

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 entit

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

Do an in-memory update

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

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

Do

the

final

Finally we do a physical commit to the actual database. Please note until we do not call SubmitCh

objContext.SubmitChanges();

The

final

create

Below

is

the

final

LINQ

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

Step

3:-

Update

So

lets

take

the

next

database

Create

data

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

DataContext objContext = new DataContext(strConnectionString);

Select

the

customer

LINQ

object

which

Get

the

LINQ

object

using

LINQ

query

wh

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

Finally

set

new

values

and

update

da

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

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

Lets DeleteOnSubmit

take

the

next

databas

We will not be going through the previous steps like creating data context and selecting LINQ object , bo the object from in-memory we need to call DeleteOnSubmit() and to delete from final database we need u

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 sh the ASP.NET UI.

DataContext objContext = new DataContext(strConnectionString);

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

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

How can we handle concurrency in LINQ?


Show/Hide Answer

LINQ gives three ways by which we can handle concurrency conflicts. To handle concurrency conflicts we catch the ChangeConflictException. We can then loop through the ChangeConflicts collection t

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

There are 3 ways provided by LINQ system KeepCurrentValues :- When this option is specified and concurrency conflicts happen LINQ keeps call th new values from the database in OverwriteCurrentValues :When this option is specified the current LINQ object KeepChanges :- This is the most weird option but can be helpful in some cases. When we talk about cla changed are kept as it is but the properties which are not changed ar We need to use the RefereshMode to specify which options we need

What is a Lambda expression?


Posted by: G_arora

A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lam expression tree types. Lambda expression uses lambda operator => Left side of this operator specifies the input parameters and contains = see how we can assign the above to a the

expre

Example: myExp Now, let

deleg

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;

No te: The

=>

operator

has

the

same

precedence

as

assignm

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such a

What is LINQ?
Posted by: Virendradugar

It stands for Language Integrated Query. LINQ is collection of standard query operators that provides t VB.NET.

How LINQ is beneficial than Stored Procedures?


Posted by: Virendradugar

There

are

couple

of

advantage

of

LINQ

1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you

2. Deployment - With stored procedures, we need to provide an additional script for stored procedures bu deployment becomes 3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good 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 b 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?


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

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

Suppose we want to combine the results from two Datasets, or we want to take a distinct valu

Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not a values. To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dign 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

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

Deployment - In case of deployment, we need to provide an additional script for stored procedures to e hence deployment b

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest compile time rather than at runtime exception.

What is the disadvantage of LINQ over stored procedures?


Posted by: Tripati_tutu

The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are precomp the execution. So according to this, I can say stored procedures are faster in performance as compared to

What are Quantifiers?


Posted by: Ddd

They

are

LINQ

Extension

methods

which

1)All 2)Any 3)Contains 4)SequenceEqual example: int[] var ------------------------------------------Output: b will return False since all elements are not > 20.

Difference between XElement and XDocument


Posted by: Ddd

Both XElement

are

the

classes

def

represents XDocument example: XDocument new new new new ) );

an class represents an entire XML document

= XElement("bookname", XElement("authorname",

When generating database mappings using LINQ to SQL, which tool allows 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 execut file, Thanks Akiii and

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 well defined interfaces.Layered architecture focuses on the grouping of related functionality within an appl of each other.Communication between layers is explicit and loosely coupled.With strict layering, compon same layer or with components from the The main Abstraction,Isolation, benefits of Manageability, the layered Performance,

N-tiers architectue usually have atleast three separate logical parts,each located on separate physical se tier is completely independent from all other tier, except for those immediately above and below it.Commu support better

The main benifit of tier 1.Maintainability. Because each tier is independent of the other tiers, updates or changes can be c

2.Scalability. Because tiers are based on the deployment of layers, scaling ou 3.Flexibility. Because each tier can be managed or scaled 4.Availability. Applications can exploit the modular architecture of enabling systems using easily scalable co

Tell me the exact difference between IQueryable and IEnumerable interfa


Posted by: Akiii

IEnumerable<T> is applicable for in-memory data querying, and in contrast IQueryable<T> allows rem

You might also like