I am updating some code which contains text-based queries into LINQ-based queries.
In this example,
var strDeviceType = "Blade";
// code edited for brevity
var strQuery = String.Format(
" SELECT Test.ID, {0}.Name AS Device " +
" FROM Test " +
" INNER JOIN {0} ON DeviceID = {0}.ID ", strDeviceType);
I have run into a problem, which is that the table being joined is specified by a string in C#. The possible values of strDeviceType are "Blade", "Engine", "Diode" (and more), and these tables are all included in my LINQ-to-SQL model.
This is a query joining the Blade table specifically
using (MyDataContext dc = new MyDataContext())
{
var result = from test in dc.Tests
join blade in dc.Blades on test.DeviceID equals blade.ID
select new { test.ID, blade.Name };
}
How would I replace ... in dc.Blades ... with the proper collection? i.e. how do I get from the string "Blade" to the collection called Blades in the model?
Here is the definition of Blade and Blades in the auto-generated model (vb.net)
<Global.System.Data.Linq.Mapping.TableAttribute(Name:="dbo.Blade")> _
Partial Public Class Blade
Implements System.ComponentModel.INotifyPropertyChanging,
System.ComponentModel.INotifyPropertyChanged
' ...
Public ReadOnly Property Blades() As System.Data.Linq.Table(Of Blade)
Get
Return Me.GetTable(Of Blade)
End Get
End Property
The other tables are defined similarly. They also have the fields ID, Name - but there is no base class or Interface which they all share which guarantees these properties.
Edit
I should have included originally that my intent is to make this query accommodate future additions of tables with ID, Name, which would be used in a similar way, without recompiling the project it is in. The project with the linq-to-sql model can be recompiled easily when tables are added.