Professional Documents
Culture Documents
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.
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
In order to understand the basic query for LINQ, lets make a small sample project. Lets take customer dat
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"}}},
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.
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.
return from clsCustomer Obj in objCustomer where Obj.customerCode == 001 select Obj;
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 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};
Order by in LINQ is pretty simple. We just need to insert order by before the Select query.
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; } }
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
The second thing is to get the entity collection using the table data type. This is done using the gettable fu
Once
we
get
all
the
data
in
table
collection
its
time
to
browse
through
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 CustomerName { set { _CustomerName = value; } get { return _CustomerName; } }
[Column(DbType = "int", IsPrimaryKey = true)] public int CustomerId { set { _CustomerId = value; } get
{ return _CustomerId; } } }
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
We The
can
instruct
LINQ
engine
to step
load
all
the is
objects
using to
DataLoadOptions. create
Below
ar
first
the
Second
step
is
to
create
th
Using the LoadWith method we need to define that we want to load customer with address in one SQL.
Every address object has phone object , so we have also defined saying that the phone objects s
Whatever
load
option
you
have
defined
you
need
to
set
the
same
to
the
objContext.LoadOptions = objDataLoadOption;
Finally
prepare
Start foreach {
looping (clsCustomerWithAddresses
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;
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
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
Step
1:-
Create
Below is the stored procedure which we will be used to flourish LINQ objects.
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;
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
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
Step
5:-
Invoke
Ok now its time to fill in the empty function GetCustomerAll. Below is the code snippet of how to exec IExecuteResult
The
object
returned
from
IExecuteResult
has
ReturnValue
property
from
which
we
can
Below
is
the
complete
code
snippet
[Function(Name = "usp_SelectCustomer", IsComposable = false)] public ISingleResult<clsCustomerEntity> getCustomerAll() { IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentM
Step
6:-
Finally
we
call
the
So
at
the
final
step
we
just
create
the
context
object
call
our
function
and
So as a first step we create the entity of customer class as shown in the below code snippet.
[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
So the first thing is to create a datacontext object using the connection string.
Once you create the connection using the DataContext object the next step is to create the customer entit
Do an in-memory update
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
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
The
final
code
of
DataContext objContext = new DataContext(strConnectionString); var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>() where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text) select objCustomer;
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();
Now on the final step selecting and reading the LINQ object by criteria. Below is the code snippet which sh the ASP.NET UI.
var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>() where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text) select objCustomer;
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
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
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
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.
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!
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 LINQ file extension that interacts with Code Behind's objects.
Posted by: Puneet20884
its .dbml
NOTE: This is objective type question, Please click question title for correct answer.
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.
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.
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
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.
Both XElement
are
the
classes
def
= 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.
They are a set of classes that takes a LINQ query and dynamically generates a sql query which is execut file, Thanks Akiii and
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
IEnumerable<T> is applicable for in-memory data querying, and in contrast IQueryable<T> allows rem