2017-02-23 55 views
-1

我正在嘗試將所有下拉列表綁定到SQL中其各自的數據庫表(僅用於測試目的)。我正在使用實體框架。我幾乎做到了,但我認爲我被困在一個無法完成的任務中(至少是不可取的),拿到DbSet無論如何。下面是代碼:從類型本身獲取類

... 
List<WebControl> myWebControl = new List<WebControl>(); 

GetWholeControls<WebControl>(Controls, ref myWebControl); //Get all the controls in the page 

myDBentity = new TimeSheetDBEntity(); /My EF 


foreach (WebControl childControl in myWebControl) //Loop all the controls 
{ 
    if (childControl is DropDownList) //Get only ddl controls 
    { 

     List<Type> typelist = (List<Type>)from p in typeof(TimeSheetDBEntity).GetProperties() 
                 where p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) 
                 select p.Name; //get all DBSet properties of my EF 

      foreach (Type currentType in typelist) //Loop the properties 
      { 
       if (childControl.ID == currentType.Name) //Compare with the ddl controls name (the first one is for example Product 
       { 

       ((DropDownList)childControl).DataSource = myDBentity.Product.ToList(); //HOW TO GET PRODUCT BACK!! 
       ((DropDownList)childControl).DataTextField = "Name"; 
       ((DropDownList)childControl).DataValueField = "Name"; 
       ((DropDownList)childControl).DataBind(); 
       }    
      } 
     } 
} 
.... 



public static void GetWholeControls<T>(ControlCollection pageControls, ref List<T> myWebControl) 
    where T : Control 
{ 
    foreach (Control control in pageControls) 
    { 
     if (control is T) 
      myWebControl.Add((T)control); 

     if (control.HasControls()) 
      GetWholeControls(control.Controls, ref myWebControl); 
    } 
} 

我想要得到的「產品」類,所以我可以得到他們的項目清單,並把它們在DDL。當然,控件名稱和類類型名稱是相同的(「Product」),並且textfield/valuefield始終爲「Name」。我認爲它不能以正常的方式實現,因爲我無法從僅在運行時已知的類型創建編譯時類型...可能使用反射或Activator.CreateInstance?...

+1

你是什麼意思「找回類」?一個新的類的例子? –

+0

同意。雜亂的代碼和糟糕的解釋。我要編輯它,試圖解釋我自己。基本上我只想在運行時獲得符合上述標準的DbSet 。 –

回答

0

實體框架上下文有一個方法按類型來獲得一組,而不是直接訪問DbSet財產

所以,與其myDBEntity.Products.ToList();,你可以調用myDBEntity.Set(currentType)AsQueryable().ToList()

https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.set(v=vs.113).aspx#M:System.Data.Entity.DbContext.Set(System.Type)

+0

感謝您的回覆。我試過這個,但是,set(Type)只返回一個DbSet而不是DbSet <>,所以恐怕我們沒有ToList()在這裏。我錯過了一個額外的步驟? –

+0

它確實返回一個DbSet類型,你可能必須把.AsQueryable(),我會更新回答 – AndrewP

+0

你的意思是? myDBentity.Set(currentType).AsQueryable()。ToListAsync()。我想你也忘了一個點。無論如何,我用另一種解決方案重寫了我的所有代碼,現在正在開展工作。感謝你的努力。 –