0% found this document useful (0 votes)
8 views

Lecture 11 - ADO.NET (Part 2)

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 11 - ADO.NET (Part 2)

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

C# 6 and the .NET 4.

6 Framework

Chapter 22: ADO.NET Part II: The


Disconnected Layer
Outline
• Understanding the Disconnected Layer of
ADO.NET
• Understanding the Role of the DataSet
• Understanding DataColumns
• Understanding DataRows
• Understanding DataTables
• Working with Data Adapters
• Programming with LINQ to DataSet
Understanding the Disconnected Layer
of ADO.NET
• Disconnected layer doesn’t maintain a connection
– You would still need data adapter to fetch and update data
– And the data adapter still needs to create a connection
• Unlike the connected layer
– Data obtained with a data adapter is not processed using data reader objects
– Adapter objects use DataSet objects (or more specifically, the DataTable objects)
• The DataSet type
– A container for any number of DataTable objects
– DataTable contains a collection of DataRow and DataColumn objects
• The data adapter object handles the database connection automatically
– Adapters keep the connection open for the shortest amount of time possible
– After having the DataSet object, the calling tier is completely disconnected from the database
and left with a local copy of the remote data
– The caller is free to insert, delete, or update rows from a given DataTable, but the physical
database is not updated until the caller explicitly passes a DataTable in the DataSet to the data
adapter for updating
Understanding the Disconnected Layer
of ADO.NET
• DataSets
– allow the clients to pretend they are always
connected;
– however, they actually operate on an in-memory
database
Understanding the Role of the DataSet
The Tables is a DataTableCollection that contains the
individual DataTables.

DataRelationCollection used to parent- child


relationships programmatically between its tables.

The ExtendedProperties property provides access to


the PropertyCollection object, which allows you to
associate any extra information to the DataSet as
name-value pairs.
Key Properties of the DataSet
Key Methods of the DataSet
Properties of DataColumn
Properties Meaning in Life
AllowDBNull You use this property to indicate whether a row can specify null values in this column. The
default value is true.
AutoIncrement You use these properties to configure the autoincrement behavior for a given column. This
can be helpful when you want to ensure unique values in a given DataColumn (such as a
primary key). By default, a DataColumn does not support autoincrement behavior.
ColumnName This property gets or sets the name of the column in the Columns collection (meaning how
it is represented internally by the DataTable). If you do not set the ColumnName explicitly,
the default values are Column with (n+1) numerical suffixes (e.g., Column1, Column2, and
Column3).
DataType This property defines the data type (e.g., Boolean, string, or float) stored in the column.
DefaultValue This property gets or sets the default value assigned to this column when you insert new
rows.
Table This property gets the DataTable that contains this DataColumn.
Unique This property gets or sets a value indicating whether the values in each row of the column
must be unique or if repeating values are permissible. If you assign a column a primary key
constraint, then you must set the Unique property to true.
Key members of DataRow
Key members of DataTable
WORKING WITH DATA ADAPTERS
Core Members of DbDataAdapter
A Simple Data Adapter Example
public static void PrintDataSet(DataSet ds)
{
Console.WriteLine($"DataSet Name: {ds.DataSetName}");
foreach (DictionaryEntry item in ds.ExtendedProperties)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
//Write the tables
foreach (DataTable tbl in ds.Tables)
{
Console.WriteLine($"Table name: {tbl.TableName}");
foreach (DataColumn col in tbl.Columns)
{
Console.Write($"{col.ColumnName}\t");
}
Console.WriteLine();

foreach (DataRow row in tbl.Rows)


{
foreach (DataColumn col in tbl.Columns)
{
Console.Write($"{row[col]}\t");
}
Console.WriteLine();
}

}
}
A Simple Data Adapter Example
public static void Main(string[] args)
{
string conStr = $"Server=localhost;Port=8889;Database=AutoLot;User=root;Password=root";
DataSet ds = new DataSet();
DbDataAdapter adapter = new MySqlDataAdapter("select * from inventory", conStr);
adapter.Fill(ds, "Inventory");
PrintDataSet(ds);
}
Mapping Database Names to Friendly
Names
public static void Main(string[] args)
{
string conStr = $"Server=localhost;Port=8889;Database=AutoLot;User=root;Password=root";
DataSet ds = new DataSet();
DbDataAdapter adapter = new MySqlDataAdapter("select * from Inventory", conStr);
adapter.TableMappings.Add("Inventory", "Current Inventory");
DataTableMapping tableMapping = adapter.TableMappings["Inventory"];
tableMapping.ColumnMappings.Add("CarId", "Car ID");
tableMapping.ColumnMappings.Add("PetName", "Name of car");
adapter.Fill(ds, "Inventory");
PrintDataSet(ds);
}
PROGRAMMING WITH LINQ TO
DATASET
LINQ over DataTable
public static void Main(string[] args)
{
string conStr = $"Server=localhost;Port=8889;Database=AutoLot;User=root;Password=root";
DataSet ds = new DataSet();
DbDataAdapter adapter = new MySqlDataAdapter("select * from Inventory", conStr);
adapter.Fill(ds, "Inventory");
We cannot use Linq over DataTable directly.
//PrintDataSet(ds);
DataTable tbl = ds.Tables[0]; We need to convert to Enumerable
var subset = from car in tbl.AsEnumerable() We need to add System.Data.DataSetExtensions to
where ((string)car["Color"]).Equals("Black") enable this
select car;
foreach (var item in subset)
{
Console.WriteLine($"{item["PetName"]} is {item["Color"]}");
}
Console.ReadLine();
}
The DataRowExtensions.Field<T>()
Extension Method
• LINQ query expression without .Field<T>()
– Uses numerous casting operations and DataRow
indexers to gather the result set
– Could result in runtime exceptions if you attempt
to cast to an incompatible data type
• Use of DataRow.Field<T>()
– To inject some strong typing into your query
– To increase the type safety of your query
– Data type is checked at Compile time
LINQ over DataTable
public static void Main(string[] args)
{
string conStr = $"Server=localhost;Port=8889;Database=AutoLot;User=root;Password=root";
DataSet ds = new DataSet();
DbDataAdapter adapter = new MySqlDataAdapter("select * from Inventory", conStr);
adapter.Fill(ds, "Inventory");
//PrintDataSet(ds);
DataTable tbl = ds.Tables[0];
var cars = from car in tbl.AsEnumerable()
where car.Field<string>("Color") == "Black"
select new
{ DataRow.Field<T> will help to check the type at
ID = car.Field<int>("CarID"), compile time
Make = car.Field<string>("Make"),
Color = car.Field<string>("Color")
};
foreach (var item in cars)
{
Console.WriteLine($"Car {item.ID} is a {item.Color} {item.Make}");
}
Console.ReadLine();
}
Hydrating New DataTables from LINQ
Queries
public static void Main(string[] args)
{
string conStr = $"Server=localhost;Port=8889;Database=AutoLot;User=root;Password=root";
DataSet ds = new DataSet();
DbDataAdapter adapter = new MySqlDataAdapter("select * from Inventory", conStr);
adapter.Fill(ds, "Inventory");
//PrintDataSet(ds);
DataTable tbl = ds.Tables[0];
var cars = from car in tbl.AsEnumerable()
where car.Field<string>("Color") == "Black"
select car; This is an extension method from
DataTable newTbl = cars.CopyToDataTable(); System.Data.DataSetExtensions
foreach (DataRow row in newTbl.Rows)
{
foreach (DataColumn col in newTbl.Columns)
{
Console.Write($"{row[col]}\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
Design for DataSet
• In class tutorial about typed dataset
– Design DataSet
– Fill data
– Insert data using typed DataSet
Summary
• Understanding the Disconnected Layer of
ADO.NET
• Understanding the Role of the DataSet
• Understanding DataColumns
• Understanding DataRows
• Understanding DataTables
• Working with Data Adapters
• Programming with LINQ to DataSet
References
Troelsen, A. & Japikse, P., 2015. C# 6 and the
.NET 4.6 Framework. 7th ed. Apress.

You might also like