2011-08-31 93 views
1

如何從db獲取列名?從ado.net實體模型獲取列名

目前,我使用ado.net實體模型通過linq-sql與db進行交互。我已經通過StackOverflow進行搜索,並獲得了一些有用的帖子,但沒有任何我已經嘗試過的。

喜歡拿這個帖子:

How do I return the column names of a LINQ entity

我試圖從康拉德Frix的反應,但他們沒有工作。無論如何,我不完全確定他的'Datacontext'是什麼意思。那個實體?

AttributeMappingSource mappping = new System.Data.Linq.Mapping.AttributeMappingSource(); 
    var model = mappping.GetModel(typeof (AdoModelEntities)); 
    var table = model.GetTable(typeof (TableName)); 

    var qFields= from fields in table.RowType.DataMembers 
      where fields.IsPersistent == true 
      select fields; 

    foreach (var field in qFields) 
     Console.WriteLine(field.Name); 

這不起作用,因爲表是空

回答

2

你可以做這樣的事情......

Object LinqObject = Activator.CreateInstance(tableName, null); 

//For each field in the database (or property in Linq object) 
foreach (PropertyInfo pi in LinqObject.GetType().GetProperties()) 
{  
    String name = pi.Name; 
} 

LinqObject將是你想上得到名稱表對象。無論您如何創建它都無關緊要。如果您只有字符串名稱,那就是創建它的一種方法。

假設你的.dbml有一個表名爲「訂單」,將工作一樣好做:

Object LinqObject = new Order(); 

您不必申報參照表對象作爲一個對象要麼很明顯。

+0

我能夠通過稍微改變一些東西來使它工作。 TableObject LinqObject = new TableObject(); – Robodude

+0

實際上,當您在發表評論時會改變這種情況,以免發生混淆。謝謝。 – Coda