检测表的主键

时间:2012-01-23 18:48:49

标签: c# reflection t4

我正在尝试生成一些自定义实体和自定义方法来从数据库中获取数据。

ListByPrimaryKey - 列名称有时是“ID”,“pid”,“id”等。

如何使用C#,使用T4模板检测列是主键?

protected void GenerateListByMethods( Table table)
{
    WriteLine("#region ListBy\n");

    WriteLine("\n\tpublic List<"+Prefix+table.Name+"> ListAll()\n\t{\n\t  " +
        this.RepositoryNotification +
        "\n\t\t\t return Ctx.GetAll().ToList().ToCustomList<"+table.Name+","+Prefix+table.Name+">();\n\t}\n");
    foreach (Column  column in table.Columns)
    {
        switch(column.DataType.Name)
        {  // do something

如何为column.DataType.IsPrimaryKey编写扩展方法?

1 个答案:

答案 0 :(得分:2)

如果您使用的是SQL SERVER,请尝试运行其中一个查询

SELECT  i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM    sys.indexes AS i INNER JOIN 
        sys.index_columns AS ic ON  i.OBJECT_ID = ic.OBJECT_ID
                                AND i.index_id = ic.index_id
WHERE   i.is_primary_key = 1

select * 
from sysobjects 
where xtype='pk' and 
   parent_obj in (select id from sysobjects where name='tablename')