So I work at a company where there are several tables with different names, but the exact same structure (date, time, value). What I would like to be able to do is have my program (C# or LINQ/LINQPad) run through these tables and query out a specific row so I can make sure they have all been updated properly. Is this doable?
So far my train of thought has been this. Knowing that each table name will give it a different class, I'm trying to generically get the values out of the table. I am able to get the table by using the code here
DataContext dc = new DataContext();
var myTable = (ITable)dc.GetType().GetProperty("Table").GetValue(dc, null);
My problem is I'm trying to get the columns out of this table using a similar method. However, the below is throwing an error:
foreach(var e in myTable)
{
double myValue = (double)e.GetType().GetProperty("Value").GetValue(e, null);
}
So when I took a look all the properties of e.GetType(), I noticed it had 2, one of which was Context, so I went exploring there. However, the next layer down seems to be a dead end of metadata with no actual data coming out of my loop. Am I even heading in the right direction? Once I get this hurdle, it would be easy enough for me to make a list and get my results out that way. Any help would be appreciated. Thanks.
If you need to query many tables by primary key (EntityKey in db context), then
ObjectContext
has a method called GetObjectByKey
that allows you to get object by EntityKey
So, you need to construct just a EntityKey. According to the MSDN article, it is pretty simple,
DataContext dc = new DataContext();
EntityKey key = new EntityKey("DataContext.Table","Id", 123);
dynamic entity = dc.GetObjectByKey(key);
You can create an interface that is common for all tables (entites) that have the same structure and cast your object to the interface, or just use dynamic
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With