Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net6.0</TargetFrameworks>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
using System;
using System.Data;
using System.Data;
using System.Data.SqlClient;

class Program
static class Program
{
static void Main()
{
}
//<Snippet1>
public static SqlDataAdapter CreateSqlDataAdapter(SqlConnection connection)
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
SqlDataAdapter adapter = new()
{
MissingSchemaAction = MissingSchemaAction.AddWithKey,

// Create the commands.
adapter.SelectCommand = new SqlCommand(
"SELECT CustomerID, CompanyName FROM CUSTOMERS", connection);
adapter.InsertCommand = new SqlCommand(
// Create the commands.
SelectCommand = new SqlCommand(
"SELECT CustomerID, CompanyName FROM CUSTOMERS", connection),
InsertCommand = new SqlCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (@CustomerID, @CompanyName)", connection);
adapter.UpdateCommand = new SqlCommand(
"VALUES (@CustomerID, @CompanyName)", connection),
UpdateCommand = new SqlCommand(
"UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
"WHERE CustomerID = @oldCustomerID", connection);
adapter.DeleteCommand = new SqlCommand(
"DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);
"WHERE CustomerID = @oldCustomerID", connection),
DeleteCommand = new SqlCommand(
"DELETE FROM Customers WHERE CustomerID = @CustomerID", connection)
};

// Create the parameters.
adapter.InsertCommand.Parameters.Add("@CustomerID",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
<AssemblyName>DP Custom CopyToDataTable Examples</AssemblyName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Data.DataSetExtensions" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace DP_Custom_CopyToDataTable_Examples
{
class Program
static class Program
{
static void Main(string[] args)
static void Main()
{
//ItemsQueries();

// JoinQuery();
// LoadScalarSequence();
// LoadItemsIntoTable();
// LoadItemsIntoExistingTable();
// JoinQuery();
// LoadScalarSequence();
// LoadItemsIntoTable();
// LoadItemsIntoExistingTable();
LoadItemsExpandSchema();

Console.WriteLine("Hit enter...");
Expand All @@ -30,8 +28,10 @@ static void JoinQuery()
{
//<SnippetJoin>
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
var ds = new DataSet
{
Locale = CultureInfo.InvariantCulture
};
FillDataSet(ds);

DataTable orders = ds.Tables["SalesOrderHeader"];
Expand All @@ -42,8 +42,8 @@ from order in orders.AsEnumerable()
join detail in details.AsEnumerable()
on order.Field<int>("SalesOrderID") equals
detail.Field<int>("SalesOrderID")
where order.Field<bool>("OnlineOrderFlag") == true
&& order.Field<DateTime>("OrderDate").Month == 8
where order.Field<bool>("OnlineOrderFlag")
&& order.Field<DateTime>("OrderDate").Month == 8
select new
{
SalesOrderID =
Expand All @@ -66,17 +66,17 @@ static void LoadItemsIntoTable()
{
//<SnippetLoadItemsIntoTable>
// Create a sequence.
Item[] items = new Item[]
var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Query for items with price greater than 9.99.
var query = from i in items
where i.Price > 9.99
orderby i.Price
select i;
IOrderedEnumerable<Item> query = from i in items
where i.Price > 9.99
orderby i.Price
select i;

// Load the query results into new DataTable.
DataTable table = query.CopyToDataTable();
Expand All @@ -88,21 +88,21 @@ static void LoadItemsIntoExistingTable()
{
//<SnippetLoadItemsIntoExistingTable>
// Create a sequence.
Item[] items = new Item[]
var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Create a table with a schema that matches that of the query results.
DataTable table = new DataTable();
var table = new DataTable();
table.Columns.Add("Price", typeof(int));
table.Columns.Add("Genre", typeof(string));

var query = from i in items
where i.Price > 9.99
orderby i.Price
select new { i.Price, i.Genre };
where i.Price > 9.99
orderby i.Price
select new { i.Price, i.Genre };

query.CopyToDataTable(table, LoadOption.PreserveChanges);
//</SnippetLoadItemsIntoExistingTable>
Expand All @@ -113,23 +113,23 @@ static void LoadItemsExpandSchema()
{
//<SnippetLoadItemsExpandSchema>
// Create a sequence.
Item[] items = new Item[]
var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Load into an existing DataTable, expand the schema and
// autogenerate a new Id.
DataTable table = new DataTable();
var table = new DataTable();
DataColumn dc = table.Columns.Add("NewId", typeof(int));
dc.AutoIncrement = true;
table.Columns.Add("ExtraColumn", typeof(string));

var query = from i in items
where i.Price > 9.99
orderby i.Price
select new { i.Price, i.Genre };
where i.Price > 9.99
orderby i.Price
select new { i.Price, i.Genre };

query.CopyToDataTable(table, LoadOption.PreserveChanges);
//</SnippetLoadItemsExpandSchema>
Expand All @@ -140,17 +140,17 @@ static void LoadScalarSequence()
{
//<SnippetLoadScalarSequence>
// Create a sequence.
Item[] items = new Item[]
var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// load sequence of scalars.
IEnumerable<double> query = from i in items
where i.Price > 9.99
orderby i.Price
select i.Price;
where i.Price > 9.99
orderby i.Price
select i.Price;

DataTable table = query.CopyToDataTable();
//</SnippetLoadScalarSequence>
Expand All @@ -159,12 +159,11 @@ orderby i.Price

static void DisplayTable(DataTable table)
{

for (int i = 0; i < table.Rows.Count; i++)
for (var i = 0; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Columns.Count; j++)
for (var j = 0; j < table.Columns.Count; j++)
{
Console.WriteLine(table.Columns[j].ColumnName + ": " + table.Rows[i][j].ToString());
Console.WriteLine(table.Columns[j].ColumnName + ": " + table.Rows[i][j]);
}
Console.WriteLine("");
}
Expand All @@ -178,10 +177,10 @@ static void FillDataSet(DataSet ds)
// Create a new adapter and give it a query to fetch sales order, contact,
// address, and product information for sales in the year 2002. Point connection
// information to the configuration setting "AdventureWorks".
string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
const string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ "Integrated Security=true;";

SqlDataAdapter da = new SqlDataAdapter(
var da = new SqlDataAdapter(
"SELECT SalesOrderID, ContactID, OrderDate, OnlineOrderFlag, " +
"TotalDue, SalesOrderNumber, Status, ShipToAddressID, BillToAddressID " +
"FROM Sales.SalesOrderHeader " +
Expand Down Expand Up @@ -227,14 +226,14 @@ static void FillDataSet(DataSet ds)
// Add data relations.
DataTable orderHeader = ds.Tables["SalesOrderHeader"];
DataTable orderDetail = ds.Tables["SalesOrderDetail"];
DataRelation order = new DataRelation("SalesOrderHeaderDetail",
var order = new DataRelation("SalesOrderHeaderDetail",
orderHeader.Columns["SalesOrderID"],
orderDetail.Columns["SalesOrderID"], true);
ds.Relations.Add(order);

DataTable contact = ds.Tables["Contact"];
DataTable orderHeader2 = ds.Tables["SalesOrderHeader"];
DataRelation orderContact = new DataRelation("SalesOrderContact",
var orderContact = new DataRelation("SalesOrderContact",
contact.Columns["ContactID"],
orderHeader2.Columns["ContactID"], true);
ds.Relations.Add(orderContact);
Expand Down Expand Up @@ -268,26 +267,22 @@ public class Movie : Item
// <SnippetCustomCopyToDataTableMethods>
public static class CustomLINQtoDataSetMethods
{
public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
{
return new ObjectShredder<T>().Shred(source, null, null);
}
public static DataTable CopyToDataTable<T>(this IEnumerable<T> source) =>
new ObjectShredder<T>().Shred(source, null, null);

public static DataTable CopyToDataTable<T>(this IEnumerable<T> source,
DataTable table, LoadOption? options)
{
return new ObjectShredder<T>().Shred(source, table, options);
}
DataTable table, LoadOption? options) =>
new ObjectShredder<T>().Shred(source, table, options);
}
// </SnippetCustomCopyToDataTableMethods>

// <SnippetObjectShredderClass>
public class ObjectShredder<T>
{
private System.Reflection.FieldInfo[] _fi;
private System.Reflection.PropertyInfo[] _pi;
private System.Collections.Generic.Dictionary<string, int> _ordinalMap;
private System.Type _type;
readonly FieldInfo[] _fi;
readonly PropertyInfo[] _pi;
readonly Dictionary<string, int> _ordinalMap;
readonly Type _type;

// ObjectShredder constructor.
public ObjectShredder()
Expand Down Expand Up @@ -324,18 +319,15 @@ public DataTable Shred(IEnumerable<T> source, DataTable table, LoadOption? optio

// Enumerate the source sequence and load the object values into rows.
table.BeginLoadData();
using (IEnumerator<T> e = source.GetEnumerator())
foreach (T item in source)
{
while (e.MoveNext())
if (options != null)
{
if (options != null)
{
table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
}
else
{
table.LoadDataRow(ShredObject(table, e.Current), true);
}
table.LoadDataRow(ShredObject(table, item), (LoadOption)options);
}
else
{
table.LoadDataRow(ShredObject(table, item), true);
}
}
table.EndLoadData();
Expand All @@ -358,7 +350,7 @@ public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOpti
table.BeginLoadData();
using (IEnumerator<T> e = source.GetEnumerator())
{
Object[] values = new object[table.Columns.Count];
var values = new object[table.Columns.Count];
while (e.MoveNext())
{
values[table.Columns["Value"].Ordinal] = e.Current;
Expand All @@ -381,7 +373,6 @@ public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOpti

public object[] ShredObject(DataTable table, T instance)
{

FieldInfo[] fi = _fi;
PropertyInfo[] pi = _pi;

Expand All @@ -395,7 +386,7 @@ public object[] ShredObject(DataTable table, T instance)
}

// Add the property and field values of the instance to an array.
Object[] values = new object[table.Columns.Count];
var values = new object[table.Columns.Count];
foreach (FieldInfo f in fi)
{
values[_ordinalMap[f.Name]] = f.GetValue(instance);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Data.DataSetExtensions" />
</ItemGroup>
Expand Down
Loading