我正在嘗試將所有下拉列表綁定到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?...
你是什麼意思「找回類」?一個新的類的例子? –
同意。雜亂的代碼和糟糕的解釋。我要編輯它,試圖解釋我自己。基本上我只想在運行時獲得符合上述標準的DbSet。 –