正在获取sql表中特定linq的名称

本文关键字:linq 获取 sql | 更新日期: 2023-09-27 17:59:41

我正在使用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));
}

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

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

但我不知道如何检索MyTables中实体的类型,这样就不必对.GetTable()的参数进行硬编码,并使其可用于我传入的任何表

C#或VB中的任何答案都可以。谢谢

编辑

总结一下我正在寻找的是一种从表本身获得表的实体类型的方法。类似Context.MyTable.GetEntityType()的东西。。。要是这么容易就好了。

正在获取sql表中特定linq的名称

我不确定这是否适用于EF,但我在Linq到Sql中使用了这种方法。

您必须使用System.Data.Linq.Mapping命名空间中的属性。如果打开*.designer.cs文件,其中包含任何Linq-to-Sql实体的定义,您会在类的声明上方找到一行类似的内容:

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

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

这也应该起作用:

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

由于我的表上没有属性,我需要获得实体名称,这是Linq to SQL在这种情况下将使用的名称,因此基于Konstantin Vasilicov的答案,扩展方法变为:

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