INTRODUCTION

Actually, I thought explaining regarding LINQ ,ENTITY FRAMEWORK..because most of the posts and queries I have seen are regarding these technologies and seems most of the developers are confused with this part of .NET Technology. But trust me LINQ is such a strong language extension which has given great power to .NET languages to query data within application only. LINQ defines a .NET application programming interface (API) and set of extensions to the Visual Basic and C# languages that enables querying diverse data types with a single syntax that ’ s similar to Structured Query Language (SQL) Which we use for database access. so Linq is

  1. Language INtegratedQuery
  2. It is part of programming language syntax
  3. Supported by: C#, VB, Delphi Prism
  4. Used for querying data
  5. Supported the following types of data sources –Relational data –XML data –objects

LINQ ARCHITECTURE

ADO .NET vs. LINQ

ADO.NET LINQ
  1. object oriented library for relational data access
  2. Mapping from relational to OO objects needed!
  3. High Impedance Missmatchfor mapping data from storage to objects in an application
  1. SQL-Like syntax that deals with pure objects
  2. Reduces the Impedance Missmatch
  3. Makes data querying more efficient
  4. One still must know the format of the data

LET US UNDERSTAND LINQ FIRST

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 from object, XML, and databases, and provides class libraries to take advantage of these capabilities. Let us see an example first. Suppose there is a list of integers as follows:

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

To find all the even numbers in this list, you might write some code as follows:

var firstList= 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 expression like this:

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

In this example, secondList and firstList 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 they be used? Let us start the exploration now. Language Integrated Query, or LINQ, is a flexible ,structured simple , SQL-like query language designed to give the programmer consistent syntax to query any data set, whether database, XML, or just plain objects. We can also take it  as It is just developed  for comfort a.

EXAMPLE: We are going to Query an Object Collection Scenario/Problem: You want to query a collection for all objects meeting some criteria. This and the following examples use some data objects to demonstrate how LINQ works.

//class declared and definition Book Antiqua";">
public class Book
{
public string Title { get; set; }
public int AuthorId { get; set; }
public int PublishYear { get; set; }
public Book(string title, int authorId, int year)
{
this.Title = title;
this.AuthorId = authorId;
this.PublishYear = year;
}
public override string ToString()
{
return string.Format(“{0} - {1}”, Title, PublishYear);
}
class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Author (int id, string firstName, string lastName)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
}
}
//...
List<Book> books = new List<Book>{
new Book(“Jack”, 1, 1941),
new Book(“Rack”,1, 1942),
new Book(“Back”,1, 1943),
 };

List authors = new List<Author>
{
new Author(1, Shabir”, Hakim”)
};
BASIC LINQ QUERY SHOWN BELOW  RETRIEVES ALL BOOK INFORMATION
 
var allBooks = from book in books select book;
foreach (Book book in allBooks)
{
Console.WriteLine(book.ToString());
}
    

The var keyword is often used with LINQ for reasons you’ll see later. In this case,allBooks is a collection of Book objects. The output is as follows:

Jack - 1841
Rack - 1842
Back - 1853 

Creating queries in LINQ is a fairly straightforward process of defining the expressions that define the nature of your operation. These expressions may be performing fi ltering, ordering, shaping, grouping, calculations, or other actions. Combining these expressions to create a query requires that you understand the basic underpinnings of LINQ and how it actually works. It is of no use simply to know how to make it do what you want. Understanding why it works that way is crucial to real understanding. Before We Understand Entity Framework,we should know why Entity Framework and Why Not Entity Framework? Entity Framework is an evolution of ADO.NET and is a data access framework comes with .NET 4.0 , Bridges the gap between database and objects(POCO) and sits on top of ADO.NET

When Not to use Framework?

 Code can only access the database through stored procedures. EF does have limited support for SP. Frequently insert operations  Bulk is not supported yet by EF Assume we want to work in a method of loading ALL data into memory is that recommended using Entity framework? What problems should we expect? Loading all entities will require many queries and a lot of time. Latencies because of the EF change tracking and large collection handling. EF contexts are not thread-safe, you should not use one context for the entire service. If you do intend to do that, use EF for loading entities, but not for managing them (detach the entities from the content). do not use the context as a cache object (for distributed scenarios) it is not thread safe, having overheads and doesn’t follow the idea of separation of concern. it is much better to use a designated cache API like AppFabric Cache.

OVERHEAD OF USING EF VS ADO.NET

The overhead of taking a ado.net data reader an transforming the results to objects, and the overhead of compiling SQL queries from LINQ. You will have the same overhead and even more, if you try to build your own ORM framework. Better don't do it When you have abstraction layer you get overhead. The overhead depends on what they do with Entity Framework. in general you should consider to get away from Inheritance because it does have a greater overhead.

Why LINQ?

In software development, the data is the main consideration. For the beginning programmer, it may seem that the world is about data entry, but at some point, it’s important to be able to evaluate data. That’s what queries are all about. For databases, the most prevalent solution has been Structured Query Language (SQL), regardless of vendor. The idea behind SQL was to provide a common way to describe the type of operation that the user wanted to perform. For example:

SELECT CustomerID, CompanyName FROM Customers WHERE
Country = 'Canada' ORDER BY CompanyName

SQL provides a simple, text-based syntax to describe the parts of a query operation (for example, SELECT, FROM, WHERE, ORDER BY, and other statements). Whether you are using SQL Server, Oracle, DB2, or even many desktop databases, the SQL syntax is strikingly similar. The basic framework of SQL was to provide a way to communicate the same ideas across different data technologies so that every vendor did not invent its own strategy for the basics of query. This is important for databases, but what about the rest of the development ecosystem? Quering database data is an obvious need, but you have to deal with other data, too. You need a solution that works with data as disparate as object graphs, Extensible Markup Language (XML) data, Web service results, and JavaScript Object Notation (JSON). You need to have a way to think about querying in a generalized way across the different sorts of data you see as a developer. That’s the purpose of LINQ. The query semantics are integrated into the languages, and it is extensible to other types of data. .NET Framework 3.5 supports LINQ against different sources including database targets, XML, and in-memory objects in the form of LINQ providers. These providers are LINQ to SQL, LINQ to XML, and LINQ . In addition, Microsoft supports LINQ for Entities to allow queries against the Entity Framework (available as part of .NET Framework 3.5 SP1). LINQ is designed so that anyone can support LINQ against data as they see fit. Many projects have included support for LINQ in nontraditional scenarios such as LINQ to Amazon and LINQ to Flickr, as well as more traditional scenarios such as third-party data frameworks (NHibernate.LINQ and LLBLGen Pro’s LINQ support). There is power in defining LINQ as the basic language of query semantics. LINQ provides a basic grammar to outline the way a query is composed. Unlike in SQL, this syntax is not text-based, which means LINQ is type-safe and compiler-validated. For example, if you use the previous query in a simple .NET Framework application, your ADO.NET code might look like this:

' VB Using conn As New SqlConnection()
Using cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT CustomerID, CompanyName " + _ " FROM
Customers " + _ " WHERE Country = 'Canada'" + _ "
ORDER BY CompanyName" ' ... End Using End Using
// C# using (SqlConnection conn = new
SqlConnection(connString)) using (SqlCommand cmd = conn.CreateCommand())
{
// SQL is Text, no way for the compiler to validate the query
cmd.CommandText = @"SELECT CustomerID, CompanyName FROM Customers WHERE Country = 'Canada'
ORDER BY CompanyName"; // ...
}

LINQ allows you to do this same work but use language-level semantics for defining your query and have it validated during compilation. Here is LINQ to SQL code that does the same thing:

' VB Using ctx = New NorthwindDataContext
Dim query = From c In ctx.Customers _ Where c.Country = "Canada" _ Order
By c.CompanyName _ Select New With {c.CompanyName, c.ContactName} End Using
// C# using (NorthwindDataContext ctx = new NorthwindDataContext())
{
var query = from c in ctx.Customers
where c.Country == "Canada" orderby
c.ContactName select new { c.CustomerID, c.CompanyName };
// ...
} 

The parts of the query syntax (for example, from, where, orderby) are integrated into the language itself. This allows you to create queries more organically than with textual SQL. This is the power of LINQ. A quick view of this example might give the impression that LINQ is just pushing database querying into the language. That would be incorrect. In fact, the purpose of LINQ is to provide a mechanism to construct queries that can be used across different problem domains.

LINQ Basics

Take a simple task as an example. Assume that you have a list of strings that represent the names to be displayed on a page. For our example, assume that you need to take this list of names and find all the names that start with a particular letter. Before LINQ, you might take this list and use foreach (or ForEach in Visual Basic) syntax to create a new list of strings to use for the page, as shown here:

 ' VB Dim names() As
String = { "Adam", "Edward", "Phillip", _ "Andrew", "Bob", "Pete", "Amy" }
Dim pageNames As New ArrayList() For Each name As String In names
If name.StartsWith("A") Then pageNames.Add(name)
End If Next name ' ...

// C# string[] names = new string[]
{ "Adam", "Edward", "Phillip", "Andrew", "Bob", "Pete", "Amy" };
ArrayList pageNames = new ArrayList(); foreach (string name in names)
{ if (name.StartsWith("A")) pageNames.Add(name); } 

This code works because you can use the foreach keyword to enumerate easily through the list of of names defined in the code. Interestingly, the foreach keyword requires that the items to be enumerated support a basic interface, IEnumerable. The IEnumerable interface specifies a way to get an enumerator object that can enumerate the list (in a forward-only fashion). That interface contract defines the requirements for what foreach does. The same holds true for LINQ. LINQ requires a basic interface to specify the basic operations for queries (including select, where, and orderby). This interface is the IEnumerable<T> interface (IEnumerable(Of T) in Visual Basic). The IEnumerable<T> interface itself is a simple extension of the IEnumerable interface to support enumerators that are type-safe. IEnumerable<T>is the interface that LINQ extends by adding extension methods for the query operations. These extension methods are part of the Enumerable class in the System.Linq namespace. The Enumerable class exposes these extension methods once you add the System.Linq namespace to your file/project. Because it uses extension methods to add this functionality, most .NET Framework collections now support this new interface. Here is that earlier example, with the extension methods to perform the same work:

 ' VB '
using System.Linq
Dim names() As String = { "Adam", "Edward", "Phillip",
_ "Andrew", "Bob", "Pete", "Amy" }
Dim pageNames() As String = _ names.Where( _ Function(name)
name.StartsWith("A") _ ).ToArray() ' ...
// C# // using System.Linq string[] names = new string[]
{ "Adam", "Edward", "Phillip", "Andrew"
, "Bob", "Pete", "Amy" };
string[] pageNames = names.Where(name => name.StartsWith("A")).ToArray();

Because the string array supports the IEnumerable<T> interface, it has the Where extension method added to support filtering the results. In this example, you are specifying a lambda to denote the actual query syntax (to find strings that start with the letter A). Finally you are calling ToArray to execute the query and return an array of strings. This works because the Where extension method returns an IEnumerable<T> reference. It’s only when you actually execute the query that the query instructions (in this case, the Where extension method) are applied against the collection. This is a key idea that is important to understand. The fact that you are calling ToArray at the end of the query should be an afterthought. For example, you can create the query and keep a reference to it for use later in your application:

 '
VB Dim names As List(Of String) =
New List(Of String) ( _ New String() {"Adam", "Edward", "Phillip",
_ "Andrew", "Bob", "Pete", "Amy"})
Dim query = names.Where(Function(name)
name.StartsWith("A"))

// C# List<string> names = new List<string>
{ "Adam", "Edward", "Phillip",
"Andrew", "Bob", "Pete", "Amy" };
var query = names.Where(name => name.StartsWith("A"));
Now with the query, you can execute the query (by calling ToArray) to get the names that match the query:
' VB ' Returns Adam, Andrew and Amy
Dim aNames() As String = query.ToArray()

// C# // Returns Adam, Andrew and Amy string[] aNames = query.ToArray();

What if you add a new name to the names collection and execute ToArray again? Will you get the same result, or will it actually re-execute the query? Here’s the result:

' VB ' Add a new Name names.Add("Alex")

' Returns Adam, Andrew, Amy and Alex aNames = query.ToArray()

// C# 
    // Add a new Name names.Add("Alex");

// Returns Adam, Andrew, Amy and Alex aNames = query.ToArray();

When you call ToArray the second time, the query is executed again. This is called deferred execution. The Where method you used earlier defined a query with a filter. When you are ready, you can call one of the execution methods (for example, any method that returns results instead of an instance of IEnumerable<T>). So far you have used only a single extension method to specify your query. You can chain them together to create more complex queries. Any query that returns an IEnumerable<T> instance supports this. For example:

' VB 
    Dim query = names.Where(Function(name) name.StartsWith("A"))
_ .OrderBy(Function(name) name) Dim pageNames() As String = query.ToArray()

// C# 
    var query = names.Where(name =>
name.StartsWith("A")) .OrderBy(name => name);
string[] pageNames = query.ToArray();

In this example, you’re still using the Where extension method to specify a lambda that is used to define the filter, but in addition, you’re adding an OrderBy extension method to sort the results that you get back from the Where extension method. Using the extension methods works, but the code is more verbose than you’d likely want. The multiple lambdas do not necessarily make the code clearer, especially as the query operations become more complex. That’s where LINQ can be a key asset. It’s hard to define LINQ. Much of what you have seen so far is really LINQ. The support for IEnumerable<T> allows for a very expressive way to define queries. To complete the circle, LINQ defines new language-level support for this mechanism. For example, you can replicate the previous query by using the language-level integration like so:

' VB 
    Dim query = From name In names _ Where
name.StartsWith("A") _ Order By name _ Select name
Dim aNames() As String = query.ToArray()


// C# 
    var query = from name in names where name.StartsWith("A")
orderby name select name; 
    string[] aNames = query.ToArray();

The syntax of the language integration is meant to look like SQL but it’s not directly analogous to SQL. It may be just syntactic sugar1, but it is a sweet treat to use. If you look back to the earlier example using the foreach syntax, you can draw the same parallel. Before foreach (before .NET Framework for most developers), you used the for keyword to perform looping (whether it was Visual Basic, C++, Java, JavaScript, or other languages):

 // JavaScript var someCollection = new Array();


// Fill the collection // Using the for keyword
to loop for (var x = 0; x < 100; x++) 
    { var item = someCollection(x); }

The addition of the foreach keyword was a shortcut for collections that were enumerable. The for keyword version of this code is not much longer than the foreach version, but it is a lot cleaner. Defi ning temporary variables (in this case, the x variable) simply to allow you to loop was unnecessary and cluttered up the code. LINQ. Most common collections (generic and nongeneric) now support this interface when used on .NET Framework 3.5). As you saw in earlier examples, LINQ doesn’t require any language changes to work. You can use extension methods to do most of the work. But LINQ’s language-level integration makes the code that much cleaner. 1 http://en.wikipedia.org/wiki/Syntactic_sugar Quick Check n What is the interface that is required for a collection to support LINQ? Quick Check Answer n The IEnumerable<T> (or IEnumerable(Of T) in Visual Basic) is required to support

To write LINQ queries,you can use free tool LINQPAD


LINQPad 5 targets .NET Framework 4.6 and includes the following features:

  1. Full C# 6 / VB14 support, including string interpolation, expression-bodied functions, exception filters, nameof, static imports and the new 'Elvis' operator.
  2. Background code-checking - both parsing and binding errors show with red squigglies. Resolved symbols display in turquoise, and unresolved symbols in red. Compilation is quicker, because most of the work is done in advance.
  3. (Pro/Premium Editions) Automatic code formatting, 'Rename Symbol', 'Jump to Definition', and 'Find References'.
  4. (Pro/Premium Editions) Autocompletion for VB, including member listings, parameter info, quick info, background compilation, smart-tags, and auto-formatting.
  5. (Pro/Premium Editions) Autocompletion for F#, inclduing member listings, parameter info and quick info.
  6. Built-in F# compiler, so fsc.exe is not required. Parsing errors are shown as you type. Autocompletion is on the way!
  7. Built-in Roslyn Syntax Tree Visualizer. The syntax tree for your query appears automatically as an output tab, and you can invoke it programmatically with .DumpSyntaxTree() or .DumpSyntaxNode().
  8. Authenticated feed support within the NuGet package manager.

If you own a Pro or Premium edition of LINQPad 4, LINQPad 5 is a paid upgrade.