SlideShare a Scribd company logo
LINQ to SQL
Agenda 
• Introduction 
• ORM—Object-Relational Mapping 
• Creating a LINQtoSQLTest Application 
• Querying and Updating the Database 
• Lazy Loading and Eager Loading 
• Joining Two Tables
Introduction 
• 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. 
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); 
} 
var list2 = from number in list where 
number % 2 == 0 select 
number;
Introduction 
• What is LINQ 
• Lambda expressions 
• Lambda expression is actually a syntax change for anonymous methods. It is just 
a new way of writing anonymous methods. Next, let's see what a lambda 
expression is step by step. 
• First, in C# 3.0, there is a new generic delegate type, Func<A,R>, which presents 
a function taking an argument of type A, and returns a value of type R: 
var veges3 = products.Get( 
delegate (Product p) { 
return p.ProductName.Contains("vegetable"); 
} 
); 
var veges4 = products.Get(p => 
p.ProductName.Contains("vegetable"));
ORM—Object-Relational Mapping 
• LINQ to SQL is considered to be one of 
Microsoft's new ORM products. So before 
we start explaining LINQ to SQL, let us 
first understand what ORM is. 
• ORM stands for Object-Relational 
Mapping. Sometimes it is called O/RM, or 
O/R mapping. It is a programming 
technique that contains a set of classes 
that map relational database entities to 
objects in a specific programming 
language.
LINQ to SQL 
• LINQ to SQL is a component of the .NET Framework 
version 3.5 that provides a run-time infrastructure for 
managing relational data as objects. 
• In LINQ to SQL, the data model of a relational 
database is mapped to an object model expressed in 
the programming language of the developer. When 
the application runs, LINQ to SQL translates the 
language-integrated queries in the object model into 
SQL and sends them to the database for execution. 
When the database returns the results, LINQ to SQL 
translates them back to objects that you can work 
with in your own programming language.
Creating a LINQtoSQL Test Application 
Adding a LINQ to SQL Item to the Project 
To start with, let’s add a new item to our project 
TestLINQToSQLApp. The new item added 
should be of type LINQ to SQL Classes, and 
named Northwind, like in the Add New Item 
dialog window shown below.
Creating a LINQtoSQL Test Application 
After you click the button Add, the 
following three files will be added to the 
project: Northwind.dbml, 
Northwind.dbml.layout, and 
Northwind.designer.cs. The first file holds 
the design interface for the database 
model, while the second one is the XML 
format of the model. Only one of them 
can remain open inside the Visual Studio 
IDE. The third one is the code-behind for 
the model which defines the DataContext 
of the model. 
At this point, the Visual Studio LINQ to 
SQL designer should be open and empty, 
like the following diagram:
Connecting to the Northwind Database 
• Open the Server Explorer window from the 
left most side of the IDE. 
• From Server Explorer, right click on Data 
Connections and select Add Connection to 
bring the add connection window.
Adding Tables and Views to the Design Surface 
• Expand the connection until all the tables 
are listed, and drag Products to the 
Northwind.dbml design surface. You should 
have a screen like in this diagram: 
• Then drag the Categories table from Server 
Explorer to the Northwind.dbml design 
surface.
Adding Tables and Views to the Design Surface 
• If you open the file Northwind.Designer.cs, 
you will find following classes are generated 
for the project: 
public partial class NorthwindDataContext : System.Data.Linq.DataContext 
public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged 
public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged 
public partial class Current_Product_List
Querying and Updating the Database 
QUERYING RECORDS 
NorthwindDataContext db = new NorthwindDataContext(); 
IEnumerable<Product> beverages = from p in db.Products 
where p.Category.CategoryName == "Beverages" 
orderby p.ProductName 
select p; 
UPDATING RECORDS 
Product bev1 = beverages.ElementAtOrDefault(10); 
if (bev1 != null) { 
Console.WriteLine("The price of {0} is {1}. Update to 20.0", bev1.ProductName, bev1.UnitPrice); 
bev1.UnitPrice = (decimal)20.00; 
} 
// submit the change to database 
db.SubmitChanges();
Querying and Updating the Database 
INSERTING RECORDS 
NorthwindDataContext db = new NorthwindDataContext(); 
Product newProduct = new Product {ProductName="new test product" }; 
db.Products.InsertOnSubmit(newProduct); 
db.SubmitChanges(); 
DELETING RECORDS 
// delete a product 
Product delProduct = (from p in db.Products 
where p.ProductName == "new test product“ 
select p).FirstOrDefault(); 
if(delProduct != null) 
db.Products.DeleteOnSubmit(delProduct); 
db.SubmitChanges();
Lazy Loading and Eager Loading 
Deferred (Lazy) Loading Versus Eager Loading 
In one of the above examples, we retrieved the category name of a product by this expression: 
p.Category.CategoryName == "Beverages" 
Even though there is no such field called category name in the Products table, we can still get the 
category name of a product because there is an association between the Products and Category table. On 
the Northwind.dbml design surface, click on the line between the Products and Categories tables and you 
will see all the properties of the association. Note, its participating properties are Category.CategoryID -> 
Product.CategoryID, meaning category ID is the key field to link these two tables. 
Because of this association, we can retrieve the category for each product, and on the other hand, we can 
also retrieve the products for each category.
Lazy Loading and Eager Loading 
Lazy Loading by Default 
However, even with the association, the associated data is not loaded when the query is executed. For example, if we retrieve all 
categories like this: 
var categories = from c in db.Categories select c; 
And later on we need to get the products for each category, the database has to be queried again. 
This is because by default, lazy loading is set to true, meaning all associated data (children) are deferred loaded until needed.
Lazy Loading and Eager Loading 
Eager Loading With Load Options 
To change this behavior, we can use the LoadWith method to tell the DataContext to automatically load the 
specified children in the initial query, like this: 
using System.Data.Linq; 
// eager loading products of categories 
DataLoadOptions dlo2 = new DataLoadOptions(); 
dlo2.LoadWith<Category>(c => c.Products); 
// create another data context, because we can't change LoadOptions of db 
// once a query has been executed against it 
NorthwindDataContext db2 = new NorthwindDataContext(); 
db2.Log = Console.Out; 
db2.LoadOptions = dlo2; 
var categories2 = from c in db2.Categories select c; 
foreach (var category2 in categories2) { 
Console.WriteLine("There are {0} products in category {1}", category2.Products.Count(), 
category2.CategoryName); 
} 
db2.Dispose();
Lazy Loading and Eager Loading 
Eager Loading With Load Options
Lazy Loading and Eager Loading 
Joining Two Tables 
var categoryProducts = from c in db.Categories 
join p in db.Products on c.CategoryID equals p.CategoryID into products 
select new {c.CategoryName, productCount = products.Count()}; 
foreach (var cp in categoryProducts) { 
Console.WriteLine("There are {0} products in category {1}", cp.CategoryName, cp.productCount); 
}
Thanks 
Prepared by: 
Muhammad Alaa

More Related Content

What's hot (18)

PPTX
Entity Framework Database and Code First
James Johnson
 
PDF
Effect systems in scala: beyond flatmap
Joost de Vries
 
PPT
5\9 SSIS 2008R2_Training - DataFlow Basics
Pramod Singla
 
PPT
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
Pramod Singla
 
PDF
Datastage Online Training
onlinetraining24
 
PPT
3.2\9 SSIS 2008R2_Training - ControlFlow Tasks
Pramod Singla
 
PPT
Data Connection using ADO DC
Purbanjali Das
 
PDF
Intake 37 linq3
Mahmoud Ouf
 
PPTX
Doctrine Data migrations | May 2017
Petr Bechyně
 
PPTX
Ef code first
ZealousysDev
 
PPT
6.1\9 SSIS 2008R2_Training - DataFlow Transformations
Pramod Singla
 
PPT
2\9.SSIS 2008R2 _Training - Control Flow
Pramod Singla
 
PPTX
Easy Dataweave transformations - Ashutosh
StrawhatLuffy11
 
PPTX
Data base connectivity and flex grid in vb
Amandeep Kaur
 
PPT
Lecture 6. ADO.NET Overview.
Alexey Furmanov
 
PPTX
Entity framework
icubesystem
 
ODP
Reactors.io
Knoldus Inc.
 
PPT
ASP.NET 09 - ADO.NET
Randy Connolly
 
Entity Framework Database and Code First
James Johnson
 
Effect systems in scala: beyond flatmap
Joost de Vries
 
5\9 SSIS 2008R2_Training - DataFlow Basics
Pramod Singla
 
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
Pramod Singla
 
Datastage Online Training
onlinetraining24
 
3.2\9 SSIS 2008R2_Training - ControlFlow Tasks
Pramod Singla
 
Data Connection using ADO DC
Purbanjali Das
 
Intake 37 linq3
Mahmoud Ouf
 
Doctrine Data migrations | May 2017
Petr Bechyně
 
Ef code first
ZealousysDev
 
6.1\9 SSIS 2008R2_Training - DataFlow Transformations
Pramod Singla
 
2\9.SSIS 2008R2 _Training - Control Flow
Pramod Singla
 
Easy Dataweave transformations - Ashutosh
StrawhatLuffy11
 
Data base connectivity and flex grid in vb
Amandeep Kaur
 
Lecture 6. ADO.NET Overview.
Alexey Furmanov
 
Entity framework
icubesystem
 
Reactors.io
Knoldus Inc.
 
ASP.NET 09 - ADO.NET
Randy Connolly
 

Similar to Linq to sql (20)

PDF
.NET Portfolio
mwillmer
 
DOCX
Db2 migration -_tips,_tricks,_and_pitfalls
sam2sung2
 
PPT
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
hammadali341730
 
PDF
3 Ways to Get Started with a React App in 2024.pdf
BOSC Tech Labs
 
PPTX
ADO.NET by ASP.NET Development Company in india
iFour Institute - Sustainable Learning
 
PDF
9 Python programming notes for ktu physics and computer application semester 4
ebindboby1
 
PPT
B_110500002
Vaibhav Chavan
 
PPTX
Entity framework
Mehdi jannati
 
PDF
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Amit Singh
 
PPTX
4 jdbc step1
myrajendra
 
PPTX
Mule dataweave
Son Nguyen
 
PPTX
Muledataweave10 161029032456-161119152200
harika thamishetti
 
ODP
Handling Database Deployments
Mike Willbanks
 
PPTX
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
DOCX
unit 3.docx
Sadhana Sreekanth
 
PDF
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
onlinetraining24
 
PDF
Online Datastage Training
onlinetraining24
 
PPT
Linq To The Enterprise
Daniel Egan
 
PDF
Fast federated SQL with Apache Calcite
Chris Baynes
 
PPTX
User Group3009
sqlserver.co.il
 
.NET Portfolio
mwillmer
 
Db2 migration -_tips,_tricks,_and_pitfalls
sam2sung2
 
MySQL, LINQ and the ADO_NET Entity Framework Presentation.ppt
hammadali341730
 
3 Ways to Get Started with a React App in 2024.pdf
BOSC Tech Labs
 
ADO.NET by ASP.NET Development Company in india
iFour Institute - Sustainable Learning
 
9 Python programming notes for ktu physics and computer application semester 4
ebindboby1
 
B_110500002
Vaibhav Chavan
 
Entity framework
Mehdi jannati
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Amit Singh
 
4 jdbc step1
myrajendra
 
Mule dataweave
Son Nguyen
 
Muledataweave10 161029032456-161119152200
harika thamishetti
 
Handling Database Deployments
Mike Willbanks
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami
 
unit 3.docx
Sadhana Sreekanth
 
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
onlinetraining24
 
Online Datastage Training
onlinetraining24
 
Linq To The Enterprise
Daniel Egan
 
Fast federated SQL with Apache Calcite
Chris Baynes
 
User Group3009
sqlserver.co.il
 
Ad

More from Muhammad Younis (11)

PPTX
Object Oriented Programming C#
Muhammad Younis
 
PPTX
Google maps api 3
Muhammad Younis
 
PPTX
Microsoft reports
Muhammad Younis
 
PPTX
Stored procedures
Muhammad Younis
 
PPTX
Mvc4
Muhammad Younis
 
PPTX
Mvc webforms
Muhammad Younis
 
PPTX
Share point overview
Muhammad Younis
 
PPTX
Lightswitch
Muhammad Younis
 
PPTX
Mvc summary
Muhammad Younis
 
PPTX
Mvc3 part2
Muhammad Younis
 
PPTX
Mvc3 part1
Muhammad Younis
 
Object Oriented Programming C#
Muhammad Younis
 
Google maps api 3
Muhammad Younis
 
Microsoft reports
Muhammad Younis
 
Stored procedures
Muhammad Younis
 
Mvc webforms
Muhammad Younis
 
Share point overview
Muhammad Younis
 
Lightswitch
Muhammad Younis
 
Mvc summary
Muhammad Younis
 
Mvc3 part2
Muhammad Younis
 
Mvc3 part1
Muhammad Younis
 
Ad

Recently uploaded (20)

PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
July Patch Tuesday
Ivanti
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 

Linq to sql

  • 2. Agenda • Introduction • ORM—Object-Relational Mapping • Creating a LINQtoSQLTest Application • Querying and Updating the Database • Lazy Loading and Eager Loading • Joining Two Tables
  • 3. Introduction • 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. 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); } var list2 = from number in list where number % 2 == 0 select number;
  • 4. Introduction • What is LINQ • Lambda expressions • Lambda expression is actually a syntax change for anonymous methods. It is just a new way of writing anonymous methods. Next, let's see what a lambda expression is step by step. • First, in C# 3.0, there is a new generic delegate type, Func<A,R>, which presents a function taking an argument of type A, and returns a value of type R: var veges3 = products.Get( delegate (Product p) { return p.ProductName.Contains("vegetable"); } ); var veges4 = products.Get(p => p.ProductName.Contains("vegetable"));
  • 5. ORM—Object-Relational Mapping • LINQ to SQL is considered to be one of Microsoft's new ORM products. So before we start explaining LINQ to SQL, let us first understand what ORM is. • ORM stands for Object-Relational Mapping. Sometimes it is called O/RM, or O/R mapping. It is a programming technique that contains a set of classes that map relational database entities to objects in a specific programming language.
  • 6. LINQ to SQL • LINQ to SQL is a component of the .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. • In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates the language-integrated queries in the object model into SQL and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.
  • 7. Creating a LINQtoSQL Test Application Adding a LINQ to SQL Item to the Project To start with, let’s add a new item to our project TestLINQToSQLApp. The new item added should be of type LINQ to SQL Classes, and named Northwind, like in the Add New Item dialog window shown below.
  • 8. Creating a LINQtoSQL Test Application After you click the button Add, the following three files will be added to the project: Northwind.dbml, Northwind.dbml.layout, and Northwind.designer.cs. The first file holds the design interface for the database model, while the second one is the XML format of the model. Only one of them can remain open inside the Visual Studio IDE. The third one is the code-behind for the model which defines the DataContext of the model. At this point, the Visual Studio LINQ to SQL designer should be open and empty, like the following diagram:
  • 9. Connecting to the Northwind Database • Open the Server Explorer window from the left most side of the IDE. • From Server Explorer, right click on Data Connections and select Add Connection to bring the add connection window.
  • 10. Adding Tables and Views to the Design Surface • Expand the connection until all the tables are listed, and drag Products to the Northwind.dbml design surface. You should have a screen like in this diagram: • Then drag the Categories table from Server Explorer to the Northwind.dbml design surface.
  • 11. Adding Tables and Views to the Design Surface • If you open the file Northwind.Designer.cs, you will find following classes are generated for the project: public partial class NorthwindDataContext : System.Data.Linq.DataContext public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged public partial class Current_Product_List
  • 12. Querying and Updating the Database QUERYING RECORDS NorthwindDataContext db = new NorthwindDataContext(); IEnumerable<Product> beverages = from p in db.Products where p.Category.CategoryName == "Beverages" orderby p.ProductName select p; UPDATING RECORDS Product bev1 = beverages.ElementAtOrDefault(10); if (bev1 != null) { Console.WriteLine("The price of {0} is {1}. Update to 20.0", bev1.ProductName, bev1.UnitPrice); bev1.UnitPrice = (decimal)20.00; } // submit the change to database db.SubmitChanges();
  • 13. Querying and Updating the Database INSERTING RECORDS NorthwindDataContext db = new NorthwindDataContext(); Product newProduct = new Product {ProductName="new test product" }; db.Products.InsertOnSubmit(newProduct); db.SubmitChanges(); DELETING RECORDS // delete a product Product delProduct = (from p in db.Products where p.ProductName == "new test product“ select p).FirstOrDefault(); if(delProduct != null) db.Products.DeleteOnSubmit(delProduct); db.SubmitChanges();
  • 14. Lazy Loading and Eager Loading Deferred (Lazy) Loading Versus Eager Loading In one of the above examples, we retrieved the category name of a product by this expression: p.Category.CategoryName == "Beverages" Even though there is no such field called category name in the Products table, we can still get the category name of a product because there is an association between the Products and Category table. On the Northwind.dbml design surface, click on the line between the Products and Categories tables and you will see all the properties of the association. Note, its participating properties are Category.CategoryID -> Product.CategoryID, meaning category ID is the key field to link these two tables. Because of this association, we can retrieve the category for each product, and on the other hand, we can also retrieve the products for each category.
  • 15. Lazy Loading and Eager Loading Lazy Loading by Default However, even with the association, the associated data is not loaded when the query is executed. For example, if we retrieve all categories like this: var categories = from c in db.Categories select c; And later on we need to get the products for each category, the database has to be queried again. This is because by default, lazy loading is set to true, meaning all associated data (children) are deferred loaded until needed.
  • 16. Lazy Loading and Eager Loading Eager Loading With Load Options To change this behavior, we can use the LoadWith method to tell the DataContext to automatically load the specified children in the initial query, like this: using System.Data.Linq; // eager loading products of categories DataLoadOptions dlo2 = new DataLoadOptions(); dlo2.LoadWith<Category>(c => c.Products); // create another data context, because we can't change LoadOptions of db // once a query has been executed against it NorthwindDataContext db2 = new NorthwindDataContext(); db2.Log = Console.Out; db2.LoadOptions = dlo2; var categories2 = from c in db2.Categories select c; foreach (var category2 in categories2) { Console.WriteLine("There are {0} products in category {1}", category2.Products.Count(), category2.CategoryName); } db2.Dispose();
  • 17. Lazy Loading and Eager Loading Eager Loading With Load Options
  • 18. Lazy Loading and Eager Loading Joining Two Tables var categoryProducts = from c in db.Categories join p in db.Products on c.CategoryID equals p.CategoryID into products select new {c.CategoryName, productCount = products.Count()}; foreach (var cp in categoryProducts) { Console.WriteLine("There are {0} products in category {1}", cp.CategoryName, cp.productCount); }
  • 19. Thanks Prepared by: Muhammad Alaa