Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting name of specific linq to sql table

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.

EDIT

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.

like image 994
yu_ominae Avatar asked Feb 15 '13 00:02

yu_ominae


2 Answers

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:

[global::System.Data.Linq.Mapping.TableAttribute(Name="YourTableName")]

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(
                           typeof(System.Data.Linq.Mapping.TableAttribute), 
                           true);
    if (temp.Length == 0)
        return null;
    else
        return (temp[0] as System.Data.Linq.Mapping.TableAttribute).Name;
}
like image 85
horgh Avatar answered Oct 12 '22 06:10

horgh


This should also work:

MyTable.Context.Mapping.GetTable(typeof(TEntity)).TableName
like image 31
Rolf Kristensen Avatar answered Oct 12 '22 06:10

Rolf Kristensen