SlideShare una empresa de Scribd logo
1 de 19
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

Más contenido relacionado

La actualidad más candente

Data base connectivity and flex grid in vb
Data base connectivity and flex grid in vbData base connectivity and flex grid in vb
Data base connectivity and flex grid in vb
Amandeep Kaur
 

La actualidad más candente (18)

Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Effect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapEffect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmap
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics
 
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
 
Datastage Online Training
Datastage Online TrainingDatastage Online Training
Datastage Online Training
 
3.2\9 SSIS 2008R2_Training - ControlFlow Tasks
3.2\9 SSIS 2008R2_Training - ControlFlow Tasks3.2\9 SSIS 2008R2_Training - ControlFlow Tasks
3.2\9 SSIS 2008R2_Training - ControlFlow Tasks
 
Data Connection using ADO DC
Data Connection using ADO DCData Connection using ADO DC
Data Connection using ADO DC
 
Intake 37 linq3
Intake 37 linq3Intake 37 linq3
Intake 37 linq3
 
Doctrine Data migrations | May 2017
Doctrine Data migrations | May 2017Doctrine Data migrations | May 2017
Doctrine Data migrations | May 2017
 
Ef code first
Ef code firstEf code first
Ef code first
 
6.1\9 SSIS 2008R2_Training - DataFlow Transformations
6.1\9 SSIS 2008R2_Training - DataFlow Transformations6.1\9 SSIS 2008R2_Training - DataFlow Transformations
6.1\9 SSIS 2008R2_Training - DataFlow Transformations
 
2\9.SSIS 2008R2 _Training - Control Flow
2\9.SSIS 2008R2 _Training - Control Flow2\9.SSIS 2008R2 _Training - Control Flow
2\9.SSIS 2008R2 _Training - Control Flow
 
Easy Dataweave transformations - Ashutosh
Easy Dataweave transformations - AshutoshEasy Dataweave transformations - Ashutosh
Easy Dataweave transformations - Ashutosh
 
Data base connectivity and flex grid in vb
Data base connectivity and flex grid in vbData base connectivity and flex grid in vb
Data base connectivity and flex grid in vb
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
Reactors.io
Reactors.ioReactors.io
Reactors.io
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 

Similar a Linq to sql

.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
Db2 migration -_tips,_tricks,_and_pitfalls
Db2 migration -_tips,_tricks,_and_pitfallsDb2 migration -_tips,_tricks,_and_pitfalls
Db2 migration -_tips,_tricks,_and_pitfalls
sam2sung2
 
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
onlinetraining24
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
Daniel Egan
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan
 

Similar a Linq to sql (20)

.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Db2 migration -_tips,_tricks,_and_pitfalls
Db2 migration -_tips,_tricks,_and_pitfallsDb2 migration -_tips,_tricks,_and_pitfalls
Db2 migration -_tips,_tricks,_and_pitfalls
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
B_110500002
B_110500002B_110500002
B_110500002
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Muledataweave10 161029032456-161119152200
Muledataweave10 161029032456-161119152200Muledataweave10 161029032456-161119152200
Muledataweave10 161029032456-161119152200
 
Mule dataweave
Mule dataweaveMule dataweave
Mule dataweave
 
Handling Database Deployments
Handling Database DeploymentsHandling Database Deployments
Handling Database Deployments
 
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
Online Datastage Training
Online Datastage TrainingOnline Datastage Training
Online Datastage Training
 
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
 
User Group3009
User Group3009User Group3009
User Group3009
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
Building AWS Redshift Data Warehouse with Matillion and Tableau
Building AWS Redshift Data Warehouse with Matillion and TableauBuilding AWS Redshift Data Warehouse with Matillion and Tableau
Building AWS Redshift Data Warehouse with Matillion and Tableau
 

Más de Muhammad Younis

Más de Muhammad Younis (11)

Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
 
Google maps api 3
Google maps api 3Google maps api 3
Google maps api 3
 
Microsoft reports
Microsoft reportsMicrosoft reports
Microsoft reports
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Mvc4
Mvc4Mvc4
Mvc4
 
Mvc webforms
Mvc webformsMvc webforms
Mvc webforms
 
Share point overview
Share point overviewShare point overview
Share point overview
 
Lightswitch
LightswitchLightswitch
Lightswitch
 
Mvc summary
Mvc summaryMvc summary
Mvc summary
 
Mvc3 part2
Mvc3   part2Mvc3   part2
Mvc3 part2
 
Mvc3 part1
Mvc3   part1Mvc3   part1
Mvc3 part1
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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