LINQ is a programming model that introduces queries as a first-class concept into any
Microsoft .NET language. However, complete support for LINQ requires some extensions in the language used. These extensions boost productivity, thereby providing a shorter, meaningful, and expressive syntax to manipulate data.
Following is a simple LINQ query for a typical software solution that returns the names of customers in Germany:
(more…)
If you want to add a record to a table or remove a record from a table, creating or deleting an object in memory is not enough. The DataContext instance must be notified also. This can be
done directly by calling Add or Remove on the corresponding Table collection (these methods
operate on the in-memory copy of the data; a subsequent SubmitChanges call will forward the
SQL commands to the database):
(more…)
One of the most frequently asked query type is outer join. With T-Sql by using ‘left outer join’ type it was possible to get the records of the Customer table without the orders.
T-Sql usage:
select c.ContactName, OrderID= case when o.OrderID is null then ‘(no orders)’ else convert(varchar,o.OrderID) end
from Customers c
left outer join Orders o on o.CustomerID = c.CustomerID
With Linq type instead of “outer” sentence, “DefaultIfEmpty()” method is used to get “left outer join”.
The usage of the T-Sql query above in Linq type:
(more…)
If you newbie to linq, you should download and install some tools for trying samples and developing apps.
Visual Studio 2008 and Sql Server express editions:
(more…)
T-Sql coalesce usage:
select c.ContactName, EmpID= coalesce(o.EmployeeID,-1)
from Customers c
left outer join Orders o on o.CustomerID = c.CustomerID
Same Query with Linq ?? operator:
(more…)
T-Sql exists Usage:
select c.CompanyName, o.*
from Customers c
join Orders o on o.CustomerId = c.CustomerId
where o.ShipCountry = ‘Germany’
Linq contains usage instead of exists:
DataClassesDataContext db = new DataClassesDataContext();
var Cust = from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID
where o.ShipCountry == “Germany”
select new { c.CompanyName, o.OrderDate, o.ShipCountry };
T-Sql exists Usage:
select *
from Customers c
where exists(select *
from Orders
where ShipCountry = ‘Germany’
and CustomerId = c.CustomerId)
Linq contains usage instead of exists:
DataClassesDataContext db = new DataClassesDataContext();
var Cust = from c in db.Customers
where (from o in db.Orders
where o.ShipCountry == “Germany”
select o.CustomerID).Contains(c.CustomerID)
select c;
Recent Comments