我正在尝试将所有下拉列表绑定到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。 –