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
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