I am wondering how I could collect data from multiple tables most deftly with C#.
I am not very used to C# and database management: I heard about ADO.NET and LINQ and the simplicity of working with tables, but I didn’t had the time to read about it, yet.
So my approach collecting data is badly complicated:
int id = 43;
var collectedData = new System.Collections.Generic.Dictionary<string, string>(); // this will later be all my collected data
// Load from first table
string select1 = "SELECT * FROM table1 WHERE ID = " + id;
DataRow dataRow1= SqlHelper.Execute.SingleRow(select1); // my helperclass returning one single data row of a table
collectedData["Surname"] = dataRow1["Surname"];
collectedData["Name"] = dataRow1["Name"];
collectedData["Age"] = dataRow1["Age"];
// Load from second table
string select2 = "SELECT * FROM table2 WHERE ID = " + id;
DataRow dataRow2= SqlHelper.Execute.SingleRow(select2);
collectedData["Mother"] = dataRow2["Mother"];
collectedData["Father"] = dataRow2["Father"];
collectedData["Job"] = dataRow2["Job"];
// ...
So how would you C# and .NET pros solve this? I am looking forward to your code samples!
If you are working with SQL Server, ADO.NET + LINQ-to-SQL is definitely the way to go.
Reasons for LINQ:
Reasons Not to Use LINQ:
For your example, you’ll want to create classes (POCO’s) that represent your database entities. Then you’ll use LINQ to query your tables and load data into the new entity objects. I prefer to have a constructor on my domain/entity objects that transform the persistent database objects generated by LINQ into domain-layer objects to be used by the client.