Getting the name of a specific linq to sql table

I use Linq to SQL for management and MS Access database.

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

I know that I can simply pass the table name as a string with hard code, for example:

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

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

I have a way to get the table name, but you need help to get thsi to work. So far I:

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

But I can’t understand how to get the type of entities in MyTablesso that there is no hard code for the argument .GetTable()and make it suitable for any table that I went to.

Any response to C # or VB is ok. Thank.

EDIT

, , . - Context.MyTable.GetEntityType()... .

+5
3

, EF, Linq to Sql.

System.Data.Linq.Mapping. *.designer.cs, Linq to Sql, , , :

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

, Linq to Sql TableAttribute, Name . :

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

:

MyTable.Context.Mapping.GetTable(typeof(TEntity)).TableName
+2

, , Linq to SQL, :

    public static string GetTableName<TEntity>(this Table<TEntity> MyTable) where TEntity : class
    {
        string name = string.Empty;
        Type type;
        object[] attributes;

        type = typeof(TEntity);
        attributes = type.GetCustomAttributes(typeof(TableAttribute), true);

        if (attributes.Length > 0)
            name = ((TableAttribute)attributes[0]).Name;
            if (!string.IsNullOrEmpty(name))
                return name;

         return type.Name;
    }
0

All Articles