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.
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;
}
This should also work:
MyTable.Context.Mapping.GetTable(typeof(TEntity)).TableName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With