Using reflection to find all linq2sql tables and ensure they match the database
- by Jake Stevenson
I'm trying to use reflection to automatically test that all my linq2sql entities match the test database. I thought I'd do this by getting all the classes that inherit from DataContext from my assembly:
var contexttypes = Assembly.GetAssembly(typeof (BaseRepository<,>)).GetTypes().Where(
t => t.IsSubclassOf(typeof(DataContext)));
foreach (var contexttype in contexttypes)
{
var context = Activator.CreateInstance(contexttype);
var tableProperties = type.GetProperties().Where(t=> t.PropertyType.Name == typeof(ITable<>).Name);
foreach (var propertyInfo in tableProperties)
{
var table = (propertyInfo.GetValue(context, null));
}
}
So far so good, this loops through each ITable< in each datacontext in the project. If I debug the code, "table" is properly instantiated, and if I expand the results view in the debugger I can see actual data.
BUT, I can't figure out how to get my code to actually query that table. I'd really like to just be able to do table.FirstOrDefault() to get the top row out of each table and make sure the SQL fetch doesn't fail. But I cant cast that table to be anything I can query.
Any suggestions on how I can make this queryable? Just the ability to call .Count() would be enough for me to ensure the entities don't have anything that doesn't match the table columns.