I’ve been trying to develop a linq query that returns the ItemNumber column of all my tables in the database, but so far I haven’t been able to do it successfully.
Basically I have a table for each kind of hardware component in a computer, and each table has a ItemNumber column. I need to query all of the tables in one bang, and return the ItemNumber values in a flat list/array. (Essentially I want to be able to do the below)
foreach (var c in items) { Console.WriteLine(c.ItemNumber); }
Searching the net to no avail, could someone show me an example of how to do this? My best attempt at it is the following, but I don’t understand Sql enough to accomplish this.
var items = from hc in dc.DataBoxPCHardwareCases from hhd in dc.DataBoxPCHardwareHardDrives from hkb in dc.DataBoxPCHardwareKeyboards from hmm in dc.DataBoxPCHardwareMemories from hmo in dc.DataBoxPCHardwareMonitors from hmb in dc.DataBoxPCHardwareMotherboards from hms in dc.DataBoxPCHardwareMouses from hod in dc.DataBoxPCHardwareOpticalDrives from hps in dc.DataBoxPCHardwarePowerSupplies from hpc in dc.DataBoxPCHardwareProcessors from hsp in dc.DataBoxPCHardwareSpeakers from hvc in dc.DataBoxPCHardwareVideoCards from sos in dc.DataBoxPCSoftwareOperatingSystems select new { hc, hhd, hkb, hmm, hmo, hmb, hms, hod, hps, hpc, hsp, hvc, sos };
What you are describing is a union:
SELECT ItemNumber FROM tbl1 UNION SELECT ItemNumber FROM tbl2
In LINQ:
Note that using UNIONs like this is not really very efficient. You are getting the entire data set in one round-trip to the database, but the database server must do a separate query for each UNION, so if you are planning on doing something complex against a lot of data, you might be better off rethinking your database design.