2011-02-04 234 views
2

我對Linq to Entities比較陌生,但我取得了很好的進展。我還沒有弄清楚的一個問題是如何從數據庫中提取列名。例如在下面的代碼中,我想用數據庫中的字段名稱替換常量。Linq to Entities To Column names

我一直沒有能夠得到我見過的工作的答案。

任何幫助將不勝感激。

鮑勃

DataTable dtNPRS = new DataTable(); 

const string kInitDate = "NPR_Init_Date"; 
const string kActive = "Active"; 
const string kStatusId = "NPR_Status_Id"; 

try 
{ 
    DataRow drNPR; 

    var nprs = (from n in db.FMCSA_NPR 
       join u in db.FMCSA_USER on n.CREATED_BY equals u.ID 
       join t in db.LKUP_NPR_TYPE on n.NPR_TYPE_ID equals t.ID 
       join s in db.LKUP_AUDIT_STATUS on n.NPR_STATUS_ID equals s.ID 
       where n.ROLE_ID == pRoleId && n.OWNER_ID == pOwnerId 
         && n.NPR_STATUS_ID == pNPRStatusId && n.ACTIVE == pActive 
       select n).ToList(); 

    if (nprs.Count() == 0) 
     return null; 

    ///build the table structure we need 
    dtNPRS.Columns.Add(kInitDate, typeof(DateTime)); 
    dtNPRS.Columns.Add(kActive,typeof(bool)); 
    dtNPRS.Columns.Add(kStatusId,typeof(Int32)); 

    foreach (var npr in nprs) 
    { 
     drNPR = dtNPRS.NewRow(); 
     drNPR[kInitDate] = npr.NPR_INIT_DATE; 
     drNPR[kActive] = npr.ACTIVE; 
     drNPR[kStatusId] = npr.NPR_STATUS_ID; 
     dtNPRS.Rows.Add(drNPR); 
    } 

    return dtNPRS; 
} 
+9

**爲什麼地球上**你是否使用像Entity Framework這樣的ORM訪問數據,然後將它轉換回程序中的行/列?這根本沒有任何意義...... **或者**保留經典的ADO.NET並使用DataTable/DataRow,**或**切換到EF然後使用**對象** - 不是你的代碼中的行和列...... – 2011-02-04 16:22:36

回答

2

到LINQ實體動態地轉換到DataTable的唯一方法就是使用反射來獲取相應的名稱:

var props = typeof(FMCSA_NPR).GetProperties(); 
foreach (var prop in props) 
{ 
    dtNPRS.Columns.Add(prop.Name, prop.PropertyType); 
} 

而一個類似的過程用於更新行:

foreach (var prop in props) 
{ 
    dtNPR[prop.Name] = prop.GetValue(npr, null); 
} 

編輯:處理可空,這樣做:

if (prop.PropertyType.Equals(typeof(Nullable<>))) 
    var type = prop.PropertyType.GetGenericArguments()[0]; 

HTH。

+0

這個確定看起來很有希望,但它試圖檢索PropertyType的第一個可空字段失敗。異常是[System.NotSupportedException] = {「DataSet不支持System.Nullable <>。」}。我的大部分字段都可以爲空 – 2011-02-04 22:19:50