Getting name of specific linq to sql table

c# entity-framework linq-to-sql


I am using Linq to SQL to manipulate and MS Access database.

To speed up batch modifications I found it more efficient to directly execute queries using the datacontext, like so context.ExecutCommand("DELETE FROM [MyTable];"). For the sake of efficiency I'd like to make this an extension method, but I don't know how to retrieve the table name from the context...

I know I could just pass the table name as a hardcoded string, something like:

public static void DeleteAll(this Table<TEntity> MyTable)
    string tableName = // retrieve MyTable's name

    MyTable.Context.ExecuteCommand(string.Format("DELETE FROM [{0}];", tableName));

I got some way towards getting the table name, but need some help to get thsi working. So far I have:

var tableName = dc.MyTables.Context.GetTable(typeof(MyTable)).ElementType.Name;

But can't figure out how to retrieve the type of the entities in MyTables so as not have to hardcode the argument of .GetTable() and make this usable for any table I pass in.

Any answer in C# or VB is fine. Thanks.


To summarise what I am looking for is a way to get the entity type of a table, from the table itself. Something like Context.MyTable.GetEntityType()... if only it were that easy.

2/15/2013 1:24:16 AM

Accepted Answer

I am not sure if this works for EF, but I use this approach in Linq to Sql.

You'll have to use attributes from System.Data.Linq.Mapping namespace. If you open the *.designer.cs file, containing the definition of any Linq to Sql entity, you'll find a line like this above the declaration of the class:


So each entity class in Linq to Sql is marked with the TableAttribute attribute and it's Name property contains the name you need. We may use this:

public static string GetTableName<TEntity>(this Table<TEntity> MyTable) 
                            where TEntity : class
    Type type = typeof(TEntity);
    object[] temp = type.GetCustomAttributes(
    if (temp.Length == 0)
        return null;
        return (temp[0] as System.Data.Linq.Mapping.TableAttribute).Name;
2/15/2013 1:12:40 AM

Popular Answer

This should also work:


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow