Asp .Net MVC - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

ASP.Net MVC LINQ

ASP.Net MVC LINQ

shape Description

LINQ means "Language Integrated Query". LINQ is a new feature  which is used to query the data. By using LINQ, one can query any type of data like XML, Relational, and Objects.  Generally, In Object Oriented Programming, Everything that deal with the class as well as the object. As a programmer, it is compulsory to learn different kinds of Query Languages. Query Languages will differ from database to database as shown in the below figure.

shape Conceptual figure

Above figure shows the different kinds of databases.

Why LINQ?

shape Description

LINQ is a Data Access Technology like ADO.Net. But Why should one use LINQ?  The answer for this question is "To avoid the Impedance Mismatch". Impedance Mismatch means the gap between the database and the objects as shown in the above figure. Here, we need OR Mapping Tools to fill the gap between Object Oriented Programming(C#.Net) and database. See the below figure, to get an idea.

shape Conceptual figure

shape Types

There are different types of OR Mapping Tools such as
  • LINQ
  • Hibernate
  • NHibernate
let's concentrate on LINQ only. LINQ was introduced in .Net framework 3.0 but, the complete implementations with all the features came in the .Net Framework3.5.

shape Conceptual figure

The complete architecture of LINQ is shown in the below figure.

shape Advantages

The below are some of the advantages of LINQ.
  • Programmer burden will decrease.
  • No need to learn different Query Languages.
  • Rapid Application Development(RAD) facilities are provided.
  • Execution of the queries will be fastest. Because Queries are executed in the front end application only.
  • Built in  Security will be provided.

Datatypes in LINQ

shape Types

There are two types of data types in LINQ
  • Named Types
  • Anonymous Types

Named Types

shape Description

Named Types are built-in types or user-defined types. In Named types, the user will decide the type of the variable.

shape Example

int a=10; double b=20.5; String s="john";

Anonymous Types

shape Description

Anonymous Types are Class Types. That means Anonymous Types are generated by the compiler. i.e, compiler will decide the type of the variable. One have to declare Anonymous Type variable using Var keyword as shown in below Example.

shape Example

Var a=10; Var b=20.5; var s="john";

Limitations of Anonymous Types

shape Limitation 1

Anonymous Types can not be used as data fields. Anonymous Types can be used as local variables only.

shape Example

[csharp] class c1 { var a = 10; //Not Allowed, Raises Compile time error public void f1() { var a = 10;//Allowed } } [/csharp]

shape Limitation 2

An Anonymous Typed Variable should be initialized.

shape Example

[csharp] var a; //Wrong var a=10; // Right [/csharp]

shape Limitation 3

To initialize multiple variables, we cannot use a single statement rather we can create multiple statements like.

shape Example

[csharp] var a=10,b=20.9,c=40; //Not allowed, Raises compiler error var a=10; //Allowed var b=20.9; //Allowed var c=40; //Allowed [/csharp]

Uses of  Anonymous types

shape Description

One can use Anonymous Types in 4 areas. They are
  • As a local variable
  • In for loop initialization
  • In for each loop initialization
  • In blocks or statements
one can also create complex types using Anonymous Types.

shape Example

[csharp] var Name=new{Name="john", FatherName="James", LastName="George"}; [/csharp] This is the example for complex types. Such kind of complex types is created by using New keyword with an initializer.

Categories in Anonymous Types

shape Types

Anonymous Types are divided as shown in the below figure.

shape Conceptual figure

Difference between Named Types and Anonymous Types

shape Table

Named Types Anonymous Types
Type is know at source time. Type is know at compile time.
User/programmer will decide the type of the variable. Complier will decide the type of the variable.
Respective type of keyword is used to create Named Type variable. Var Keyword is used to create Anonymous Type variable.
Named Type Variable can be used as Local/Global Variable Anonymous Type Variable can be used as Local Variable only.
Named Type Variable can be used in any context Anonymous Type Variable can be used in the following contexts only.
  • As local variable
  • in statements
  • in for loop and for each loop initialization
Initialization of variable is optional. initialization of variable is mandatory.
Suppoert Unary Operators(increment/decrement)like a=a++ Does not support Unary Operations(increment/decrement)like a=a++
One can declare multiple variables in same statement. One cannot declare multiple variables in same statement.
Primitive Types do not support complex types. Support complex types.

Example for Anonymous Types

shape Example 1

[csharp] static void main() { var a = 10; var b = 30.6; var s = "John"; Console.WriteLine("value of a is" + a); Console.WriteLine("value of b is" + b); Console.WriteLine("value of c is" + s); Console.ReadLine(); } [/csharp]

shape Example 2

[csharp] static void main() { string[] Names = { "John", "Devid", "James" }; Console.WriteLine("List Of Names are:"); foreach(var x in Names) { Console.WriteLine(x + ""); } Console.ReadLine(); } [/csharp]

shape Example 3

[csharp] static void main() { var Names =new { FirstName="John",SecondName="Devid", ThirdName="James" }; Console.WriteLine("Names are:"+Names.FirstName+Names.SecondName+Names.ThirdName); Console.ReadLine(); } [/csharp] These are the some of the examples for Anonymous Types.

Anonymous Functions

shape Description

Anonymous Function is introduced in .Net Framework 2.0. An Anonymous Function is a function which is similar to standard functions. Anonymous Functions also take the inputs and gives the outputs. The only difference between the standard functions and the Anonymous Function is Name. In general, Anonymous Functions are used within Delegates or Lambda Expressions.

shape Example

[csharp] namespace AnonymousFunctionExample { class Example { delegate void sampledelegate(string s);//Anonymous Function with in the delegate static void main() { sampledelegate obj=delegate(string s) { Console.WriteLine("Value is:"+s); }; obj("James"); Console.ReadLine(); } } } [/csharp] See the above example. Above example shows the Anonymous Function with in the delegate.

Lambda Expression

shape Description

A  Lambda Expression is an anonymous function or method which returns a value. Lambda Expression derived from a mathematical term 'Lambda'.  Lambda Expression decrease the burden on the programmer. By using Lambda Expression, one can write an anonymous function without a delegate.  

shape Syntax

Arguments=>Body of the Function or Expression. Here,'=>' indicates the Lambda Expression.

shape Example

X=>X*X The above Expression implies that X goes to X*X Here, the first value i.e X means the arguments in the function and the second value i.e X*X means the Expression.

Difference between An Anonymous function and a Lambda Expression

shape Description

See the below examples to know the difference between An anonymous function and a lambda expression.

shape Example 1

[csharp] //An anonymous function delegate int mul(int i); mul obj= delegate(int value) { return (value*2); }; int i = obj(10); [/csharp]

shape Example 2

[csharp] //Lambda Expression <span class="code-keyword">delegate</span> <span class="code-keyword">int mul</span> <span class="code-keyword">int(i) mul obj</span> <span class="code-keyword">value=></span> <span class="code-keyword">value*</span> <span class="code-digit">2</span> <span class="code-keyword">int i = obj</span> <span class="code-digit">20</span>[/csharp] Observe the difference between above two examples. Lambda Expression reduces the code and decreases the burden on the programmer.

Types of  Lambda Expression

shape Types

There are two categories under the Lambda Expression.
  • Expression Lambdas
  • Statement Lambdas

Expression Lambdas

shape Description

See the syntax of the Lambda Expression. The right-hand side of the syntax i.e expression is called as Expression Lambdas. Expression Lambdas are used in the Expression Trees. Mainly the Expression Lambda returns the result of the expression.

shape Example

[csharp] delegate int cube(int x); static void main() { cube obj = a =<a * a * a;//calculates the cube value of given value int Result = obj(2); // pass the value to lambda expression Console.WriteLine("Cube Value is" + Result); //displays the result } [/csharp]

Statement Lambdas

shape Description

Statement Lambdas is also in the right-hand side of the Lambda Operator. But, Statement Lambdas contains two or more statements which are enclosed in the braces.

shape Syntax

(Arguments)=>{Statements;} Statement Lambdas are not used for constructing Expression Trees.

Working with Object Initializer

shape Description

Object initializer is a new feature of C# 3.0 version. Object initializer is used to simplify the object construction. See the below example which shows a normal object declaration.

shape Example

[csharp] class person { //Properties public int Name { get; set; } public string Age { get; set; } } //To create an object for the above class, we can write the following piece of code in C# 2.0 Person obj = new Person(); obj.Name="James"; obj.Age=30; [/csharp] But In C# 3.0, it is provided with the object initializer which reduces a little burden. See the below code to know Object initializer. [csharp] class person { //Properties public int Name { get; set; } public string Age { get; set; } } Person obj=new Person{Name="James",Age=30}; [/csharp] One can also use the nested concept here. That means, one can declare the object with in the object by using this object initializer.

Working with collection initializer

shape Description

Collection initializer is also a new feature which is introduced in the C# 3.0. Collection initializer is used to initialize the collection.

shape Types

The C# supports 3 types of collections.
  • Normal Collections
  • Specialized Collections
  • Generic Collections
Normal Collections are like Array list, Stack, Queue, and Hash Table. Specialized Collections are like List Dictionary, String Dictionary, and String Collection. Generic Collections are like following List() Stack() HashList()

shape Syntax

CollectionType<datatype> CollectionName=new CollectionType<datatype>{Initializing values separeted with ','};

shape Example

[csharp] class Employee { // Auto-implemented properties. public int EmpId { get; set; } public string EmpName { get; set; } public int EmpAge { get; set; } } class Example { static void main() { List<Employee> employee= new List<Employee>() { new Employee{EmpId=1,EmpName="James",EmpAge=23} new Employee{EmpId=2,EmpName="Jan",EmpAge=43} }; foreach(var x in employee) { Console.WriteLine(+x.EmpId+x.EmpName+x.EmpAge); } Console.ReadLine(); } } [/csharp]

Queries in LINQ

shape Description

A Query is a type of language which is used to communicate with the Database and returns some Output or Data. In LINQ, a Query is always will work on some data source which is inherited from the iEnumerable interface. LINQ Query contains 3 parts.
  • From Clause
  • Select Clause
  • Where Clause

shape Methods

To execute the Query, there are two methods in LINQ.
  1. Differed Execution
  2. Forced Immediate Execution
Differed Execution In this method, Query will be executed when a foreach loop is iterated. As long as the loop is being  iterated query will be running. To print the elements, One have to use the for each loop. [csharp] foreach(var x in R) { Console.WriteLine(X+""); } [/csharp] Forced Immediate Execution In this method, Query will be run and it will return the result immediately. If one want to print the count of elements, Then write the code as shown below. [csharp] Console.WriteLne("Count of Elemts is"+R.Count()); [/csharp] Here, when using R.Count() immediately Query will be run & will return the result, and query will be run only once.

Steps to work with LINQ Query

shape Step 1

Obtain the Data Source. Example: List<int> L1=new List<int>{1,2,3,4,5}

shape Step 2

Prepare Query. Example: var R= from Num in L1 where Num% 2==0 select Num;

shape Step 3

Execute the Query.

OR Mapping Tool

shape Description

OR Mapping Tool means Object Relational Mapping Tool. OR Mapping Tool is used to build a bridge between Database and the Object Oriented Programming(C# or VB).

shape Conceptual figure

The following diagram shows you the relation between them. OR Mapping Tool is used to map the database structure into the front end. Here, it will be converted completely into "Object Oriented Programming Format".
  • In general. the database what we mapped will be converted into the class by adding "Data Context" word at the end.
  • This class contains a method known as "Submit Changes". This method is used to save the modifications made in the data back to the database.
  • A class will be created on the Table Name and the Fields of the table will become as Properties.
  • As well as the class which created with the table name will become as a property in the Data Context class.

Data Context Class

shape Description

Data Context Class also contains two methods.
  • Insert on Submit (Table Class Type)
  • Delete on Submit (Table Class Type)
Insert on Submit Insert on Submit is used to insert a record into the respective table when the data context class sends the request to database. Delete on Submit Delete on submit is used to delete a record from the respective table when the data context class sends the request to database.

shape Conceptual figure

The following figure shows the structure when mapping takes place.