简体   繁体   English

如何获取列名WebMatrix.Data

[英]How to get column names WebMatrix.Data

Trying to figure out how to get the column names from the SQL statement. 试图找出如何从SQL语句中获取列名。 Saw something online that says this works, but surely it doesn't: 在网上看到一些说有用的东西,但肯定不会:

 var rows=db.Query("select * from users");

 <ul>
     @foreach(var col in rows)
     {
         <li>@col.name</li>
     }
 </ul>

This displays the value only if there is a column with the name name , but I'd like the actual column name if possible. 仅当存在具有名称name的列时才显示该值,但是如果可能,我想要实际的列名称。

Anyone know how to get all the column names using WebMatrix.Data ? 任何人都知道如何使用WebMatrix.Data获取所有列名称?

EDIT: 编辑:

Looks like the DynamicRecord Class exposes the column names, just wondering how it applies. 看起来DynamicRecord类公开了列名,只是想知道它是如何应用的。 http://msdn.microsoft.com/en-us/library/webmatrix.data.dynamicrecord(v=vs.111).aspx http://msdn.microsoft.com/en-us/library/webmatrix.data.dynamicrecord(v=vs.111).aspx

You can use the GetDynamicMemberNames method to obtain the "columns" (which have been converted to dynamic properties) 您可以使用GetDynamicMemberNames方法获取“列”(已转换为动态属性)

var rows = db.Query("select * from users");

 <ul>
     @foreach(var item in rows.First().GetDynamicMemberNames())
     {
         <li>row[item]</li>
     }
 </ul>

Ok let me explain this for you. 好吧,让我为你解释一下。

I have created a new project and tested it in the Visual Studio and it works. 我已经创建了一个新项目,并在Visual Studio中对其进行了测试,但它确实有效。 You need to udnerstand the basics about the DynamicRecord and the property of the Columns. 您需要了解有关DynamicRecord和Columns属性的基础知识。

Here is the code that I have used, 这是我用过的代码,

@{ 
    var db = Database.Open("StarterSite");
    var selectQuery = "SELECT * FROM UserProfile";
    var result = db.Query(selectQuery);
}

In the HTML I did this, 在HTML中我做了这个,

<div>
    @foreach (var row in result)
    {
        <p>@row.Columns[0]</p>
    }
</div>

When it executed, since the DynamicRecord.Columns property is an IList<string> generic type, so you should understand that you can read their properties through a simple indexation. 执行时,由于DynamicRecord.Columns属性是IList<string>泛型类型,因此您应该了解可以通过简单的索引来读取它们的属性。 Like the one I have done, it will read the first column from the List of the strings that was sent down to the user. 就像我所做的那样,它将读取发送给用户的字符串列表中的第一列。

Now when it executed, since the very first column was Email , it gave me the following output on screen. 现在当它执行时,由于第一列是电子邮件 ,它在屏幕上给了我以下输出。

在此输入图像描述

You can get others from the list too. 您也可以从列表中获取其他人。 Just update the index number. 只需更新索引号即可。 :-) :-)

http://msdn.microsoft.com/en-us/library/webmatrix.data.dynamicrecord.columns(v=vs.111).aspx http://msdn.microsoft.com/en-us/library/webmatrix.data.dynamicrecord.columns(v=vs.111).aspx

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

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