gpt4 book ai didi

c# - 获取特定 linq to sql 表的名称

转载 作者:太空狗 更新时间:2023-10-29 20:13:55 26 4
gpt4 key购买 nike

我正在使用 Linq to SQL 来操作 MS Access 数据库。

为了加快批量修改,我发现使用数据上下文直接执行查询更有效,例如 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));
}

我有一些方法可以获取表名,但需要一些帮助才能使它正常工作。到目前为止,我有:

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

但无法弄清楚如何检索 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")]

因此,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;
}

关于c# - 获取特定 linq to sql 表的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14886725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com