SlideShare a Scribd company logo
1 of 18
Download to read offline
Language INtegrated Query
(LINQ)
Eng. Mahmoud Ouf
Lecture 3
mmouf@2017
LINQ to ADO.NET
LINQ to ADO.NET API provides some additional types and
infrastructure to enable LINQ/database integration.
LINQ to ADO.NET is a blanket term that describes two database-centric
aspects of LINQ.
First we have LINQ to DataSet.
This API is essentially a set of extensions to the standard ADO.NET
DataSet programming model that allows DataSets, DataTables, and
DataRows to be a natural target for a LINQ query expression.
Second component of LINQ to ADO.NET is LINQ to SQL.
This API allows you to interact with a relational database by abstracting
away the underlying ADO.NET data types (connections, commands,
data adapters, etc.) through the use of entity classes.
mmouf@2017
LINQ to DataSet
DataSet type is the center piece of the disconnected layer and is used to
represent a cached copy of interrelated DataTable objects and
(optionally) the relationships between them.
So, We have to Query over the DataTable.
But…
DataTable doesn’t implement IEnumerable<T>
So…
We need to change it to get a LINQ Compatible DataTable by:
using the AsEnumerable() Method of the DataTable, which return:
EnumerableRowCollection
mmouf@2017
LINQ to DataSet
public static void Main
{
//Assume there is a dataset (ds) contains a DataTable (Department)
// Get a DataTable containing the current Table
DataTable dept = ds.Tables[“Department”];
// Get enumerable version of DataTable.
EnumerableRowCollection enumData = dept.AsEnumerable();
// OR Store return value as IEnumerable<T>.
IEnumerable<DataRow> enumData = dept.AsEnumerable();
//OR Store return value implicitly.
var enumData = dept.AsEnumerable();
mmouf@2017
LINQ to DataSet
//Query on the LINQ Compatible DataTable
var query = from d in enumData
select new
{
DepartmentId = (int)d["DepartmentId"],
DepartmentName = (string)d["Name"]
};
//Execute the Query
foreach (var q in query)
Console.WriteLine("Department Id = {0} , Name = {1}",
q.DepartmentId, q.DepartmentName);
}
mmouf@2017
LINQ to DataSet
public static void Main
{
//Assume there is a dataset (ds) contains a 2 DataTables
//(Department) and (Employee) with a relation between them
// Get a DataTable containing the current Table
DataTable dept = ds.Tables["Department"];
DataTable emp = ds.Tables["Employee"];
// Get enumerable version of DataTable.
EnumerableRowCollection enumDept = dept.AsEnumerable();
EnumerableRowCollection enumEmp = emp.AsEnumerable();
mmouf@2017
LINQ to DataSet
//Query on the LINQ Compatible DataTable
var query = from d in enumDept
join e in enumEmp
on (int)d["DepartmentId“] equals(int)e["DepartmentId“]
select new
{
EmployeeId = (int)e["EmployeeId“],
Name = (string)e["Name“],
DepartmentId = (int)d["DepartmentId“],
DepartmentName = (string)d["Name“]
};
mmouf@2017
LINQ to DataSet
//Execute the Query
foreach (var q in query)
{
Console.WriteLine("Employee Id = {0} , Name = {1} ,
Department Name = {2}", q.EmployeeId, q.Name,
q.DepartmentName);
}
Console.ReadLine();
}
mmouf@2017
LINQ to SQL
LINQ to SQL is an API that allows you to apply well-formed LINQ
query expressions to data held within relational databases.
LINQ to SQL provides a number of types that facilitate the
communication between your code base and the physical database
engine.
The major goal of LINQ to SQL is to provide consistency between
relational databases and the programming logic used to interact with
them.
Rather than having to treat relational data as a stream of records, we are
able to interact with the data using standard object-oriented
programming techniques.
Given the fact that LINQ to SQL allows us to integrate data access
directly within our C# code base
mmouf@2017
LINQ to SQL
When programming with LINQ to SQL, you see no trace of common
ADO.NET types such as SqlConnection, SqlCommand, or
SqlDataAdapter.
Using LINQ query expressions, entity classes and the DataContext type,
you are able to perform all the expected database CRUD (create,
remove, update, and delete), as well as define transactional contexts,
create new database entities (or entire databases), invoke stored
procedures, and perform other database-centric activities.
mmouf@2017
LINQ to SQL
Entity Class
Entity classes are types that represent the relational data you wish to
interact with.
Programmatically speaking, entity classes are class definitions that are
annotated with various LINQ to SQL attributes (such as [Table] and
[Column]) that map to a physical table in a specific database.
DataContext class
This class type is in charge of translating your LINQ query expressions
into proper SQL queries as well as communicating with the specified
database.
mmouf@2017
LINQ to SQL(example)
[Table]
public class Inventory
{
[Column]
public string Make;
[Column]
public string Color;
[Column]
public string PetName;
// Identify the primary key.
[Column(IsPrimaryKey = true)]
public int CarID;
public override string ToString()
{
return string.Format("ID = {0}; Make = {1}; Color = {2}; PetName = {3}", CarID,
Make.Trim(), Color.Trim(), PetName.Trim());
}
}
mmouf@2017
LINQ to SQL(example)
Insert a new object:
1. Create an object from the appropriate entity class
2. Fill the created object with data
3. Use the InsertOnSubmit() Method, defined in the collection named
with the entity class name (plural) in the DataContext object
4. Use SubmitChanges() Method defined in DataContext object
static void InsertNewCars(AutoLotObjectsDataContext ctx)
{
Console.Write("Enter ID for Betty: ");
int newCarID = int.Parse(Console.ReadLine());
// Create object from Inventory (step 1)
Inventory newCar = new Inventory();
mmouf@2017
LINQ to SQL(example)
//Fill the object with data (step 2)
newCar.Make = "Yugo";
newCar.Color = "Pink";
newCar.PetName = "Betty";
newCar.CarID = newCarID;
//Call InsertOnSubmit() Method (step 3)
ctx.Inventories.InsertOnSubmit(newCar);
//Call SubmitChanges() Method (step 4)
ctx.SubmitChanges();
}
mmouf@2017
LINQ to SQL(example)
Update an existing object:
1. Get a Reference to the Row you want to update
2. Update the Row data
3. Use SubmitChanges() Method defined in DataContext object
static void UpdateCar(AutoLotObjectsDataContext ctx)
{
// Update Betty's color to light pink. (step 1)
var betty = (from c in ctx.Inventories
where c.PetName == "Betty"
select c).First();
betty.Color = "Green"; // (step 2)
ctx.SubmitChanges(); // (step 3)
}
mmouf@2017
LINQ to SQL(example)
Delete an existing object:
1. Get a Reference to the Row you want to update
2. Use the DeleteOnSubmit() Method, defined in the collection named
with the entity class name (plural) in the DataContext object
3. Use SubmitChanges() Method defined in DataContext object
static void DeleteCar(AutoLotObjectsDataContext ctx)
{
Console.Write("Enter ID of car to delete: ");
int carToDelete = int.Parse(Console.ReadLine());
// Remove specified car. (step 1)
var car = (from c in ctx.Inventories
where c.CarID == carToDelete
select c).First();
mmouf@2017
LINQ to SQL(example)
//(step 2)
ctx.Inventories.DeleteOnSubmit(car);
//(step 3)
ctx.SubmitChanges();
}
mmouf@2017
LINQ to SQL(with visual studio)
1. Create a new Project (Solution is Created)
2. Add a new Project to the Solution:
Solution Explorer (R.C.) Project Name Add New Item
3. Choose “LINQ to SQL classes
4. From the “Server Explorer”, make a new connection and Drag the
Required Tables
mmouf@2017

More Related Content

What's hot

Language Integrated Query By Nyros Developer
Language Integrated Query By Nyros DeveloperLanguage Integrated Query By Nyros Developer
Language Integrated Query By Nyros DeveloperNyros Technologies
 
Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Mohamed Saleh
 
Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQDoncho Minkov
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RRsquared Academy
 
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadIntroduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadNicheTech Com. Solutions Pvt. Ltd.
 
R Programming: Getting Help In R
R Programming: Getting Help In RR Programming: Getting Help In R
R Programming: Getting Help In RRsquared Academy
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 

What's hot (20)

Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
Linq
LinqLinq
Linq
 
Language Integrated Query By Nyros Developer
Language Integrated Query By Nyros DeveloperLanguage Integrated Query By Nyros Developer
Language Integrated Query By Nyros Developer
 
Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)
 
Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQ
 
Intake 37 ef1
Intake 37 ef1Intake 37 ef1
Intake 37 ef1
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In R
 
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadIntroduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
R Programming: Getting Help In R
R Programming: Getting Help In RR Programming: Getting Help In R
R Programming: Getting Help In R
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Intake 38_1
Intake 38_1Intake 38_1
Intake 38_1
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 

Viewers also liked

Rutina de Pensamiento "Jorge Rando"
Rutina de Pensamiento "Jorge Rando"Rutina de Pensamiento "Jorge Rando"
Rutina de Pensamiento "Jorge Rando"Alquimista Aula
 
Tile - Nooit meer je waardevolle spullen kwijt
Tile - Nooit meer je waardevolle spullen kwijtTile - Nooit meer je waardevolle spullen kwijt
Tile - Nooit meer je waardevolle spullen kwijtWillem van Grasstek
 
Analyzing_Data_with_Spark_and_Cassandra
Analyzing_Data_with_Spark_and_CassandraAnalyzing_Data_with_Spark_and_Cassandra
Analyzing_Data_with_Spark_and_CassandraRich Beaudoin
 
Autos híbridos cap1
Autos híbridos cap1Autos híbridos cap1
Autos híbridos cap1Jack Vásquez
 
Customer Management Infographic - Forrester Report
Customer Management Infographic - Forrester ReportCustomer Management Infographic - Forrester Report
Customer Management Infographic - Forrester ReportOmer Celep
 
Tecnologías de-la-información-y-la-comunicación (2)
Tecnologías de-la-información-y-la-comunicación (2)Tecnologías de-la-información-y-la-comunicación (2)
Tecnologías de-la-información-y-la-comunicación (2)Norman Lucero
 
Identificación das árbores celtas do
Identificación das árbores celtas doIdentificación das árbores celtas do
Identificación das árbores celtas doradiorasca
 
Software craftmanship coaching
Software craftmanship coachingSoftware craftmanship coaching
Software craftmanship coachingPedro Santos
 
Shakespeare
ShakespeareShakespeare
Shakespearerafa
 

Viewers also liked (18)

Abhilekh rris
Abhilekh rrisAbhilekh rris
Abhilekh rris
 
Rutina de Pensamiento "Jorge Rando"
Rutina de Pensamiento "Jorge Rando"Rutina de Pensamiento "Jorge Rando"
Rutina de Pensamiento "Jorge Rando"
 
Kinds of tests
Kinds of testsKinds of tests
Kinds of tests
 
євро2015
євро2015євро2015
євро2015
 
Padrasto
PadrastoPadrasto
Padrasto
 
Practica e xcel 2
Practica e xcel 2 Practica e xcel 2
Practica e xcel 2
 
Tile - Nooit meer je waardevolle spullen kwijt
Tile - Nooit meer je waardevolle spullen kwijtTile - Nooit meer je waardevolle spullen kwijt
Tile - Nooit meer je waardevolle spullen kwijt
 
Anna
AnnaAnna
Anna
 
Analyzing_Data_with_Spark_and_Cassandra
Analyzing_Data_with_Spark_and_CassandraAnalyzing_Data_with_Spark_and_Cassandra
Analyzing_Data_with_Spark_and_Cassandra
 
SI YO FUERA...
SI YO FUERA...SI YO FUERA...
SI YO FUERA...
 
Autos híbridos cap1
Autos híbridos cap1Autos híbridos cap1
Autos híbridos cap1
 
Customer Management Infographic - Forrester Report
Customer Management Infographic - Forrester ReportCustomer Management Infographic - Forrester Report
Customer Management Infographic - Forrester Report
 
Tecnologías de-la-información-y-la-comunicación (2)
Tecnologías de-la-información-y-la-comunicación (2)Tecnologías de-la-información-y-la-comunicación (2)
Tecnologías de-la-información-y-la-comunicación (2)
 
Identificación das árbores celtas do
Identificación das árbores celtas doIdentificación das árbores celtas do
Identificación das árbores celtas do
 
Software craftmanship coaching
Software craftmanship coachingSoftware craftmanship coaching
Software craftmanship coaching
 
Acrilico
AcrilicoAcrilico
Acrilico
 
Crime museum
Crime museumCrime museum
Crime museum
 
Shakespeare
ShakespeareShakespeare
Shakespeare
 

Similar to Intake 37 linq3

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.netNgeam Soly
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to adoHarman Bajwa
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Servicesukdpe
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETEverywhere
 

Similar to Intake 37 linq3 (20)

B_110500002
B_110500002B_110500002
B_110500002
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
 
Olap
OlapOlap
Olap
 
Ado.net
Ado.netAdo.net
Ado.net
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
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
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
SetFocus Portfolio
SetFocus PortfolioSetFocus Portfolio
SetFocus Portfolio
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
 
Linq
LinqLinq
Linq
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 

More from Mahmoud Ouf

More from Mahmoud Ouf (16)

Relation between classes in arabic
Relation between classes in arabicRelation between classes in arabic
Relation between classes in arabic
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1
 
Intake 38 11
Intake 38 11Intake 38 11
Intake 38 11
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Intake 37 DM
Intake 37 DMIntake 37 DM
Intake 37 DM
 
Intake 37 12
Intake 37 12Intake 37 12
Intake 37 12
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Intake 37 10
Intake 37 10Intake 37 10
Intake 37 10
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Intake 37 8
Intake 37 8Intake 37 8
Intake 37 8
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 

Recently uploaded

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Intake 37 linq3

  • 1. Language INtegrated Query (LINQ) Eng. Mahmoud Ouf Lecture 3 mmouf@2017
  • 2. LINQ to ADO.NET LINQ to ADO.NET API provides some additional types and infrastructure to enable LINQ/database integration. LINQ to ADO.NET is a blanket term that describes two database-centric aspects of LINQ. First we have LINQ to DataSet. This API is essentially a set of extensions to the standard ADO.NET DataSet programming model that allows DataSets, DataTables, and DataRows to be a natural target for a LINQ query expression. Second component of LINQ to ADO.NET is LINQ to SQL. This API allows you to interact with a relational database by abstracting away the underlying ADO.NET data types (connections, commands, data adapters, etc.) through the use of entity classes. mmouf@2017
  • 3. LINQ to DataSet DataSet type is the center piece of the disconnected layer and is used to represent a cached copy of interrelated DataTable objects and (optionally) the relationships between them. So, We have to Query over the DataTable. But… DataTable doesn’t implement IEnumerable<T> So… We need to change it to get a LINQ Compatible DataTable by: using the AsEnumerable() Method of the DataTable, which return: EnumerableRowCollection mmouf@2017
  • 4. LINQ to DataSet public static void Main { //Assume there is a dataset (ds) contains a DataTable (Department) // Get a DataTable containing the current Table DataTable dept = ds.Tables[“Department”]; // Get enumerable version of DataTable. EnumerableRowCollection enumData = dept.AsEnumerable(); // OR Store return value as IEnumerable<T>. IEnumerable<DataRow> enumData = dept.AsEnumerable(); //OR Store return value implicitly. var enumData = dept.AsEnumerable(); mmouf@2017
  • 5. LINQ to DataSet //Query on the LINQ Compatible DataTable var query = from d in enumData select new { DepartmentId = (int)d["DepartmentId"], DepartmentName = (string)d["Name"] }; //Execute the Query foreach (var q in query) Console.WriteLine("Department Id = {0} , Name = {1}", q.DepartmentId, q.DepartmentName); } mmouf@2017
  • 6. LINQ to DataSet public static void Main { //Assume there is a dataset (ds) contains a 2 DataTables //(Department) and (Employee) with a relation between them // Get a DataTable containing the current Table DataTable dept = ds.Tables["Department"]; DataTable emp = ds.Tables["Employee"]; // Get enumerable version of DataTable. EnumerableRowCollection enumDept = dept.AsEnumerable(); EnumerableRowCollection enumEmp = emp.AsEnumerable(); mmouf@2017
  • 7. LINQ to DataSet //Query on the LINQ Compatible DataTable var query = from d in enumDept join e in enumEmp on (int)d["DepartmentId“] equals(int)e["DepartmentId“] select new { EmployeeId = (int)e["EmployeeId“], Name = (string)e["Name“], DepartmentId = (int)d["DepartmentId“], DepartmentName = (string)d["Name“] }; mmouf@2017
  • 8. LINQ to DataSet //Execute the Query foreach (var q in query) { Console.WriteLine("Employee Id = {0} , Name = {1} , Department Name = {2}", q.EmployeeId, q.Name, q.DepartmentName); } Console.ReadLine(); } mmouf@2017
  • 9. LINQ to SQL LINQ to SQL is an API that allows you to apply well-formed LINQ query expressions to data held within relational databases. LINQ to SQL provides a number of types that facilitate the communication between your code base and the physical database engine. The major goal of LINQ to SQL is to provide consistency between relational databases and the programming logic used to interact with them. Rather than having to treat relational data as a stream of records, we are able to interact with the data using standard object-oriented programming techniques. Given the fact that LINQ to SQL allows us to integrate data access directly within our C# code base mmouf@2017
  • 10. LINQ to SQL When programming with LINQ to SQL, you see no trace of common ADO.NET types such as SqlConnection, SqlCommand, or SqlDataAdapter. Using LINQ query expressions, entity classes and the DataContext type, you are able to perform all the expected database CRUD (create, remove, update, and delete), as well as define transactional contexts, create new database entities (or entire databases), invoke stored procedures, and perform other database-centric activities. mmouf@2017
  • 11. LINQ to SQL Entity Class Entity classes are types that represent the relational data you wish to interact with. Programmatically speaking, entity classes are class definitions that are annotated with various LINQ to SQL attributes (such as [Table] and [Column]) that map to a physical table in a specific database. DataContext class This class type is in charge of translating your LINQ query expressions into proper SQL queries as well as communicating with the specified database. mmouf@2017
  • 12. LINQ to SQL(example) [Table] public class Inventory { [Column] public string Make; [Column] public string Color; [Column] public string PetName; // Identify the primary key. [Column(IsPrimaryKey = true)] public int CarID; public override string ToString() { return string.Format("ID = {0}; Make = {1}; Color = {2}; PetName = {3}", CarID, Make.Trim(), Color.Trim(), PetName.Trim()); } } mmouf@2017
  • 13. LINQ to SQL(example) Insert a new object: 1. Create an object from the appropriate entity class 2. Fill the created object with data 3. Use the InsertOnSubmit() Method, defined in the collection named with the entity class name (plural) in the DataContext object 4. Use SubmitChanges() Method defined in DataContext object static void InsertNewCars(AutoLotObjectsDataContext ctx) { Console.Write("Enter ID for Betty: "); int newCarID = int.Parse(Console.ReadLine()); // Create object from Inventory (step 1) Inventory newCar = new Inventory(); mmouf@2017
  • 14. LINQ to SQL(example) //Fill the object with data (step 2) newCar.Make = "Yugo"; newCar.Color = "Pink"; newCar.PetName = "Betty"; newCar.CarID = newCarID; //Call InsertOnSubmit() Method (step 3) ctx.Inventories.InsertOnSubmit(newCar); //Call SubmitChanges() Method (step 4) ctx.SubmitChanges(); } mmouf@2017
  • 15. LINQ to SQL(example) Update an existing object: 1. Get a Reference to the Row you want to update 2. Update the Row data 3. Use SubmitChanges() Method defined in DataContext object static void UpdateCar(AutoLotObjectsDataContext ctx) { // Update Betty's color to light pink. (step 1) var betty = (from c in ctx.Inventories where c.PetName == "Betty" select c).First(); betty.Color = "Green"; // (step 2) ctx.SubmitChanges(); // (step 3) } mmouf@2017
  • 16. LINQ to SQL(example) Delete an existing object: 1. Get a Reference to the Row you want to update 2. Use the DeleteOnSubmit() Method, defined in the collection named with the entity class name (plural) in the DataContext object 3. Use SubmitChanges() Method defined in DataContext object static void DeleteCar(AutoLotObjectsDataContext ctx) { Console.Write("Enter ID of car to delete: "); int carToDelete = int.Parse(Console.ReadLine()); // Remove specified car. (step 1) var car = (from c in ctx.Inventories where c.CarID == carToDelete select c).First(); mmouf@2017
  • 17. LINQ to SQL(example) //(step 2) ctx.Inventories.DeleteOnSubmit(car); //(step 3) ctx.SubmitChanges(); } mmouf@2017
  • 18. LINQ to SQL(with visual studio) 1. Create a new Project (Solution is Created) 2. Add a new Project to the Solution: Solution Explorer (R.C.) Project Name Add New Item 3. Choose “LINQ to SQL classes 4. From the “Server Explorer”, make a new connection and Drag the Required Tables mmouf@2017