views:

960

answers:

2

I have a DataContext (Linq to Sql) with over 100 tables, is it possible to get a list of all those tables and lets say print them to the console? This might be a silly question.

Thanks.

+2  A: 

You can do this via reflection. Essentially, you iterate over the properties in your DataContext class. For each property, check to see if that property's generic parameter type has the TableAttribute attribute. If so, that property represents a table:

using System.Reflection;
using System.Data.Linq.Mappings;

PropertyInfo[] properties = typeof(MyDataContext).GetProperties();
foreach (PropertyInfo property in properties)
{
    if(property.PropertyType.IsGenericType)
    {
        object[] attribs = property.PropertyType.GetGenericArguments()[0].GetCustomAttributes(typeof(TableAttribute), false);
        if(attribs.Length > 0)
        {
            Console.WriteLine(property.Name);
        }
    }
}
Rex M
Damn it! You type too fast :P
SirDemon
@SirDemon actually i completely got the answer wrong, deleted it, tested the right answer in Visual Studio, undeleted and revised :)
Rex M
haha thank you very much, that was fast!
McLovin
Fast, but a bit over-complex when the Mapping property is right there in Linq to SQL.
Jacob Proffitt
+10  A: 

It's much easier than above and no reflection required. Linq to SQL has a Mapping property that you can use to get an enumeration of all the tables.

context.Mapping.GetTables();
Jacob Proffitt
Nice, I did not know about that.
Rex M
whooo hoo that's even better!
McLovin
Yeah, I keep finding stuff like that myself. It's always fun to pass one on :).
Jacob Proffitt