Getting name of specific linq to sql table

c# entity-framework linq-to-sql vb.net

Question

I am modifying an MS Access database using Linq to SQL.

I discovered that leveraging the datacontext to directly perform queries to speed up batch updates was more effective.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 am aware that I could simply supply the table name as a hardcoded string, 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. I have thus far:

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

However, I'm having trouble figuring out how to extract the entities' type inMyTables so as not to have the argument of hardcoding.GetTable() and allow me to use this at whatever table I pass.

Any C# or VB response is acceptable. Thanks.

EDIT

In a nutshell, I'm seeking for a means to determine an entity type from a table directly. something similarContext.MyTable.GetEntityType() If only everything were that simple.

1
8
2/15/2013 1:24:16 AM

Accepted Answer

I use this method in Linq to Sql, however I'm not sure if it works with EF.

You'll need to employ characteristics fromSystem.Data.Linq.Mapping namespace. Upon opening the*.designer.cs You can locate a line similar to this one above the declaration of the class in any file that contains the definition of a Linq to Sql entity:

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

In Linq to SQL, each entity class is therefore annotated with theTableAttribute a quality, and it'sName 'property' has the name you require. We could employ 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;
}
9
2/15/2013 1:12:40 AM

Popular Answer

This ought to work as well:

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


Related Questions





Related

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