yu_*_*nae 7 c# vb.net entity-framework linq-to-sql
我正在使用Linq to SQL来操作和MS Access数据库.
为了加快批量修改,我发现使用datacontext直接执行查询更有效,就像这样context.ExecutCommand("DELETE FROM [MyTable];").为了提高效率,我想将其作为扩展方法,但我不知道如何从上下文中检索表名...
我知道我可以将表名称作为硬编码字符串传递,例如:
public static void DeleteAll(this Table<TEntity> MyTable)
{
string tableName = // retrieve MyTable's name
MyTable.Context.ExecuteCommand(string.Format("DELETE FROM [{0}];", tableName));
}
Run Code Online (Sandbox Code Playgroud)
我在获取表名方面有所帮助,但需要一些帮助才能获得工作.到目前为止,我有:
var tableName = dc.MyTables.Context.GetTable(typeof(MyTable)).ElementType.Name;
Run Code Online (Sandbox Code Playgroud)
但无法弄清楚如何检索实体的类型,MyTables以便不必硬编码参数,.GetTable()并使其可用于我传入的任何表.
在C#或VB中的任何答案都可以.谢谢.
编辑
总结我正在寻找的是一种从表本身获取表的实体类型的方法.有点像Context.MyTable.GetEntityType()...如果只是那么容易.
我不确定这是否适用于EF,但我在Linq to Sql中使用这种方法.
您必须使用System.Data.Linq.Mapping命名空间中的属性.如果你打开*.designer.cs文件,包含任何Linq to Sql实体的定义,你会在类的声明上面找到这样的一行:
[global::System.Data.Linq.Mapping.TableAttribute(Name="YourTableName")]
Run Code Online (Sandbox Code Playgroud)
因此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;
}
Run Code Online (Sandbox Code Playgroud)