简体   繁体   English

从数据库中的表获取列名

[英]Get columns name from a table in database

in my database i have many of tables one of Tables is nambed Company ". and its columns names are as follows ("ComName","ComAddress","ComType" ..etc) I have a function which get the columns name from Company table : 在我的数据库中,我有很多表,其中的一个表被Company命名为“。”,其列名称如下("ComName","ComAddress","ComType" ..etc)我有一个从Company获得列名称的函数。表:

public List<string> GetColumnNames(string tablename)
{
    var names = typeof(Company).GetProperties().Select(p => p.Name).ToArray();
    return names.ToList();
}

Until now everything is good but what if i want to get the columns of other tables ? 到目前为止,一切都很好,但是如果我想获取其他表的列怎么办? so i have to put the name of the new table (that is given in the function as "tablename") instead of "Company" in this sentence : 所以我必须在这句话中放入新表的名称(在函数中以“ tablename”给出),而不是“ Company”:

var names = typeof(Company).GetProperties().Select(p => p.Name).ToArray();

but it is string so its not working. 但它是字符串,因此无法正常工作。 any idea ? 任何想法 ?

typeof(Company).GetProperties() isn't fetching the names of the columns of your table at all though - it's fetching the names of the properties of the C# class/entity that you're using to represent that table. typeof(Company).GetProperties()根本不获取表的列名称-而是获取用于表示该表的C#类/实体的属性的名称。 Do you already have a process to guarantee you have C# entities with property names that exactly match the column names of your tables? 您是否已经有一个过程来确保您拥有的C#实体的属性名称与表的列名称完全匹配? If so, you can do the same principle (but instead of using typeof(Company) you'd need to find the type by name, which there are various ways of doing). 如果是这样,您可以执行相同的原理(但是,除了使用typeof(Company)之外,您还需要按名称查找类型,这有多种实现方式)。 If not, you'll need to to actually query the database to find the column names. 如果不是,则需要实际查询数据库以查找列名。

As far as i know, you can use the Type parameter. 据我所知,您可以使用Type参数。

public List<string> GetColumnNames(Type tablename)
{

    var names = tablename.GetProperties().Select(p => p.Name).ToArray();

    return names.ToList();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM