ASP.NET - LINQ in asp.net

Asked By kiruba .e
29-Nov-11 01:40 AM
I want to know the very basics of linq in asp.net?


How to use this in asp.net?


Regards
kiruba.e
  Vickey F replied to kiruba .e
29-Nov-11 01:41 AM
Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. MSDN has a popular set of samples that demonstrate various aspects of LINQ, samples for both Visual C# and Visual Basic. These cover a range of areas, including restriction operators, grouping operators, aggregate operators, and a lot more.

 
Follow this link , here you will get basic examples-

http://msdn.microsoft.com/en-us/vstudio/aa336746
  Suchit shah replied to kiruba .e
29-Nov-11 01:46 AM

What is the purpose of LINQ Providers in LINQ?

LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source.

What are the four LINQ Providers that .NET Framework ships?

1. LINQ to Objects - Executes a LINQ query against a collection of objects

2. LINQ to XML - Executes an XPATH query against XML documents

3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.

4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.


What is LINQ

Language-Integrated Query (LINQ) is a set of extensions to the .NET  Framework that encompass language-integrated query, set, and transform  operations. It extends C# and Visual Basic with native language syntax  for queries and provides class libraries to take advantage of these
capabilities.

Let us see an example first. Suppose there is a list of integers like this:


List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 100 };

To find all the even numbers in this list, you might write code like this:

List<int> list1 = new List<int>();
foreach (var num in list)
{
    if (num % 2 == 0)
      list1.Add(num);
}

Now with LINQ, you can select all of the even numbers from this list  and assign the query result to a variable, in just one sentence, like  this:

var list2 = from number in list
        where number % 2 == 0
        select number;

In this example, list2 and list1 are equivalent. list2 contains the same numbers as list1 does. As you can see, you don't write a foreach loop. Instead, you write a SQL statement.

But what do from, where, and select mean here? Where are they defined? How and when can you use them? Let us start the exploration now.

  James H replied to kiruba .e
29-Nov-11 01:48 AM

Linq is the Microsoft's first attempt to integrate queries into language. We know, it is really easy to find data from sql objects simply writing a query while its somewhat hectic when we want to do the same thing in a DataTable or Lists. Generally we will have to loop through every elements to find the exact match, if there is some aggregation we need to aggregate the values etc. Linq provides an easy way to write queries that can run with the in memory objects.  

Types of LINQ 

Linq Comes with 3 Basic Types (Provided there are lots of more types of LINQ on different type of objects :

1. LINQ (Linq to Objects)
2. DLINQ (Linq to SQL)
3. XLINQ (Linq to XML)


Before we continue with LINQ, we must look at some of the new inclusions which may come to us very handy.http://www.worldofasp.net/tut/LINQ/Basic_introduction_of_LINQ_205.aspx
http://www.codeproject.com/KB/dotnet/LINQ.aspx

  Riley K replied to kiruba .e
29-Nov-11 01:50 AM
LINQ offers a great way to query database model where the whole logical model of the database is generated in the form of entities


You can also query on collections


Suppose to select all rows from table we use Select * from Emp


In LINQ we car assign the results to a Var type or List


  Var results=From n in dc.Employee
                        select n;



to query two tables, an example we can use is using the Northwind database.  Let's assume we want to join the Customers and Orders tables together

We would write a query like this to retrieve the OrderID, and OrderDate from the Order table, and the CustomerID and ContactName from the Customer table:

class Program
  {
  static void Main(string[] args)
  {
    using (DataClasses1DataContext db = new DataClasses1DataContext())
    {
 
 
    var query_results = from d in db.Customers
          join o in db.Orders
          on d.CustomerID equals o.CustomerID
          select new { o.OrderID, o.OrderDate, d.CustomerID, d.ContactName };
      
 
 
    }
  }
   
 
 
}



 You can refer 101 LINQ samples
http://

Regards
  Suchit shah replied to kiruba .e
29-Nov-11 01:55 AM

I am going to discuss the basic SQL queries and the LINQ queries similar to SQL queries, with visual representations of the LINQ queries. Before I start discussing, here is the structure of the table I am using for this article:

Users

01_userclient_table.png

UserClients

02_user_table.png

LINQ structure

03_linq_structure.png

List of LINQ Queries

Case 1: Select

The SQL query to get all users from the user table with all columns would be:

The LINQ query to do the above is:

var user = from u in Users
select u;

Here is the graphical representation the break down of the LINQ query that you wrote to get data form the user table:

04_select_user.png

Case 2: Select with Columns

This case is similar to the above but the difference is we are not selecting all the columns; instead, I select only two columns: FirstName and LastName. The SQL query to select all rows with only two columns is:

Select FirstName, LastName from [User]

Now the LINQ query:

from u in Users
select new
{
    u.FirstName,
    u.LastName
};

So you need to create a new anonymous type to get only the FirstName and LastName form the user object. The graphical representation of this query is:

05_select_user.png

Case 3: Filter Selected Data

For Integer Data

To apply filter on the selected data, we use the WHERE clause with the column value, so the SQL query would be:

Select firstname,LastName from [User] where id = 3

In LINQ, we need to use the WHERE clause as well, so the query would be:

from u in Users
where u.Id ==3
select new
{
   u.FirstName,
   u.LastName
}

This graphical representation shows the breakdown of the LINQ query related to filtering data:

06_select_filter.png

For String Data

In order to filter strings, we use LIKE:

SELECT  [Id], [FirstName], [LastName], [Email], 
        [DisplayName], [Address1], [Address2], [Password], [Role]
FROM [User]
WHERE [Email] LIKE '%pranay%'

or

SELECT  [Id], [FirstName], [LastName], [Email], 
        [DisplayName], [Address1], [Address2], [Password], [Role]
FROM [User]
WHERE [Email] LIKE 'pranay%'

To apply the filter on the string datatype, you need to use the Contains or StartWith function available in C# so that it generates the same result as the above SQL queries:

from u in Users
where u.Email.Contains ("pranay")
select u

or

from u in Users
where u.Email.StartsWith ("pranay")
select u

The graphical representation of the LINQ query filtering using a string field:

07_select_filter_like.png

Case 4: Joining Two Tables

Inner Join

Inner join is how we can get common records between two tables, i.e., related records form the table(s). Here is a SQL query for an inner join:

SELECT [User].[Id], [FirstName], [LastName], [UserId], [MobileNo]
FROM [User]
INNER JOIN
[UserClients]
ON [User].[id] = [UserId]

LINQ does the same using the Join keyword with Equals to join two collections:

var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
select new {
  u.Id,
  u.FirstName,
  u.LastName,
  uc.MobileNo,
  uc.imeiNO,
  uc.Id,
};

The graphical representation of inner join for the LINQ query is as shown below. As you can see, the User connection gets added to UserClients based on the condition in On.. Equals:

Outer Join

Outer Join is how we get common records between two tables, i.e., related records form a table; all records from the left table and not found in the right table gets a null value. A SQL query for an outer join would look like:

SELECT [t0].[Id], [FirstName], [LastName], 
       [UserId] AS [UserId], [MobileNo] AS [MobileNo]
FROM [User] AS [t0]
LEFT OUTER JOIN [UserClients]  ON ([t0].[id]) = [UserId]

In LINQ, to achieve outer join, you need to use the DefaultIfEmpty() function like:

var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
 u.Id,
 u.FirstName,
 u.LastName,
 m.UserId,
 m.MobileNo
};

The graphical representation of the outer join LINQ query is same as that for the inner join, but there is one more step for the function DefaultIfEmpty():

Case 5: Ordering Data

In SQL to order fetched data, we need to apply the ORDER BY clause with the ASC or DESC keyword, so the SQL query would be:

--Ascending
Select * from [User] order by firstName

or:

--Descending
Select * from [User] order by firstName desc

LINQ uses ORDER BY combined with the ASCENDING and DESCENDING keywords so that the final LINQ query would be:

//Ascending
var user = from u in Users
orderby u.FirstName
 select new
{
   u.FirstName,
   u.LastName 
}

or

//Descending
var user = from u in Users
orderby u.FirstName descending
select new
{
   u.FirstName,
   u.LastName 
};

Here is the graphical breakdown of the LINQ query:

Case 6: Grouping Data

Groups of selected data allow to perform aggregate function likes SUM, MAX, MIN, COUNT etc. To group data in SQL, you need to use the GROUP BY clause, but the thing to remember is you need to include the select list column in your group by clause or you will get a syntax error:

SELECT COUNT(*) AS [test], [UserId]
FROM [UserClients]
GROUP BY [UserId]

LINQ uses Group ... By to group data, so the query looks like:

var user =  from u in UserClients
group u by u.UserId into c
select new
{
 t1 = c.Key,
 tcount = c.Count()
};

Note: After you apply group by on a collection of objects in LINQ, your group by column gets converted to a key column which you can see in the above LINQ query, UserId. The graphical breakdown of the Group...By LINQ query is:

Case 7: Filter Data Using IN and NOT IN Clauses

Most developers who start working on LINQ queries get confused when they have to write IN and NOT IN queries using LINQ. Here is the SQL query:

//IN
SELECT [Id], [UserId], [IMEINo]
FROM [UserClients]
WHERE [UserId] IN (3, 4)

or:

//NOT IN
SELECT [Id], [UserId],  [IMEINo]
FROM [UserClients]
WHERE [UserId] IN (3, 4)

As you see above, the query uses IN and NOT IN clauses to filter from a list of records. The LINQ query to achieve this task makes use of the Contains function of C#, which does filtering of records from a list of records:

//IN
int[] chosenOnes = { 3, 4 };
var user = from u in UserClients
where chosenOnes.Contains(u.UserId.Value)
select new  { u.id,u.userid, u.ImeiNo};

or:

//NOT IN
int[] chosenOnes = { 3, 4 };
var user = from u in UserClients
where !chosenOnes.Contains(u.UserId.Value)
select u;

Note: IN and NOT IN use the same function in the LINQ query, but it just use a ! (not) symbol for it. Here is the graphical representation:

Case 8: Filtering Data by Row Numbers

I am now going to show how you can filter your data by row numbers that you assigned to your record(s). To filter data in SQL Server (SQL Server 2005), we use the http://msdn.microsoft.com/en-us/library/ms186734.aspx function and then we use <=, >=, or BETWEEN. Here is the SQL query:

SELECT *
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [id]) AS [ROW_NUMBER],
           [id], [FirstName], [LastName], [Email], [DisplayName], 
           [Address1], [Address2], [Password], [Role]
    FROM [User] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN 11 AND 20
ORDER BY [t1].[ROW_NUMBER]

In the above query, as you can see, the ROW_NUMBER() function assigns a number to the records, and we can use that number in an outer query to filter data between 11 to 20. LINQ makes use of two functions:

  • Skip: Bypasses a specified number of elements in a sequence and then returns the remaining elements
  • Take: Returns a specified number of contiguous elements from the start of a sequence

The LINQ query is something like:

var users = from u in Users
select u;

var filterUsers= users.OrderBy (p => p.Id).Skip (10).Take(10);

In the above code, we are selecting data first and than we are applying Skip and Take to get data between the 11 to 20 records. Here is the graphical representation;

 

Case 9: SQL ISNULL function

Solution 1

We can use the ternary operator as in the below example and MobileNo = "N/A" for the null values:

var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
UserId = m.UserId,
MobileNo = (m.MobileNo == null) ? "N/A" : m.MobileNo
};

Solution 2

Use the special Coalescing operator operator (??) as in the below example, and MobileNo = "N/A" for the null values:

var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
UserId = m.UserId,
MobileNo = m.MobileNo == null ?? "N/A" 
};
  Reena Jain replied to kiruba .e
29-Nov-11 01:59 AM
hi,

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

Featured Information
    Essential LINQ (Microsoft .NET Development Series)

LINQ is one of Microsoft’s most exciting, powerful new development technologies.Essential LINQ is the first LINQ book written by leading members of Microsoft’s LINQ and C# teams.
LINQ to XML

LINQ to XML was developed with Language-Integrated Query over XML in mind and takes advantage of standard query operators and adds query extensions specific to XML.

Follow these googd links-

http://msdn.microsoft.com/en-us/netframework/aa904594
http://msdn.microsoft.com/en-us/library/bb308959.aspx

Hope this will help you.
  kiruba .e replied to Suchit shah
29-Nov-11 02:16 AM
thanks buddy....and should i instal any softwre for this? where to write and test linq?
  kalpana aparnathi replied to kiruba .e
29-Nov-11 03:29 AM
hi,

http://http://msdn.microsoft.com/en-us/library/bb907622.aspx
  Suchit shah replied to kiruba .e
29-Nov-11 04:42 AM
In your application if you want to Right LINQ query then you can right it in to the Your Visual Studio application itself

and before implementing this on applicaiton if you want to check the result throught query the You should have to check with Editor
Generally LINQ Pad is used as a Editor to fire the LINQ query

If you just Google it out and search for "Download LINQ Pad" you will easily find it is size is not more than 5 MB
Hope it helps
  Suchit shah replied to kiruba .e
29-Nov-11 04:42 AM
In your application if you want to Right LINQ query then you can right it in to the Your Visual Studio application itself

and before implementing this on applicaiton if you want to check the result throught query the You should have to check with Editor
Generally LINQ Pad is used as a Editor to fire the LINQ query

If you just Google it out and search for "Download LINQ Pad" you will easily find it is size is not more than 5 MB
Hope it helps
Create New Account
help
visual studio installation problem Actually, my OS is Windows Xp with service pack2.I added service pack3 to install visual studio2010.after that i tryed to installed, but am getting SETUP FAILED due to "Windows XP is not installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio Macro Tools was not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates .NET Framework 4 Multi-Targeting Pack was not attempted to be installed. [08 / 10 / 11, 14:26
Frequently asked Interview Questions in ADO.Net hi friends Any one send frequently asked Important questions in C# .Net, ADO .Net, Asp .Net and Sql Server. . . . . . . . tx in Advance. . . . . . Hi, Find this. . (B)What is an IL? (B)What is a B) What is concept of Boxing and Unboxing ? (B) What is the difference between VB.NET and C#? (I) what is the difference between System exceptions and Application exceptions? (I)What is CODE Access security? (I)What is a satellite assembly? (A) How to prevent my .NET DLL to be decompiled? (I) what is the difference between Convert.toString and .toString () method
all, i like to setup a fast clonable test / development installation of MOSS2007 under Windows 2008 SP1 (not R2) (32bit). As starting point I have choosen the Blog post from here This means the installation should be on a single server as Domain Controller , as MS SQL database server and as MOSS2007 server farm. Only one uses should be used. Thats what I have done, I followed the I am reading the logfiles placed under "c: \ program files \ common files \ microsoft shared \ web server extensions \ 12 \ logs". I don't find any relavant information regarding authentication or what else von der Anmeldung angeforderte 'SharePoint_07_Config'-Datenbank kann nicht geöffnet werden. Fehler bei der Anmeldung.' Source: '.Net SqlClient Data Provider' Number: 4060 State: 1 Class: 11 Procedure: '' LineNumber: 65536 Server: 'd-it5-sptest-dc' 03 / 04 / 2010 13:53:11.35 OWSTIMER.EXE (0x0980) 0x0988
linq to sql hi all, i want to know how to retrive the data from database to front linq.so pls give me detail explanation. hi sasi Whether you are working with ADO.NET datasets, SQL databases, .NET collections, or XML documents, the basic structure of a LINQ query expression is the same be executed or modified any number of times. Query expression syntax resembles the syntax of SQL. For example, you could write a LINQ query that returns all students in a students studentQuery = from student in studentApp.students where student.Major = = "Science" select student; Use LINQ to SQL to access SQL Server and SQL Server Express databases through a strongly-typed object layer that you create by