2009-04-09 14 views

risposta

28

È molto più facile di quanto sopra e non è necessaria alcuna riflessione. Da Linq a SQL è disponibile una proprietà Mapping che è possibile utilizzare per ottenere un'enumerazione di tutte le tabelle.

context.Mapping.GetTables(); 
+0

Bello, non lo sapevo. –

+0

whooo hoo è ancora meglio! – Sergey

+0

Sì, continuo a cercare cose del genere da solo. È sempre divertente passarne uno :). –

4

È possibile farlo tramite riflessione. In sostanza, si esegue l'iterazione sulle proprietà nella classe DataContext. Per ogni proprietà, verificare se il tipo di parametro generico di quella proprietà ha l'attributo TableAttribute. In tal caso, quella proprietà rappresenta una tabella:

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); 
     } 
    } 
} 
+0

Dannazione! Digitate troppo velocemente: P – SirDemon

+0

@SirDemon in realtà ho completamente sbagliato la risposta, cancellato, testato la risposta giusta in Visual Studio, non cancellato e revisionato :) –

+0

haha ​​grazie mille, è stato veloce! – Sergey

3
dc= new myDataContext(); 
var listaTablas = (from tables in dc.Mapping.GetTables() select tables.TableName).ToList(); 
1
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); 
     } 
    } 
} 
Problemi correlati