【发布时间】:2017-02-23 22:19:17
【问题描述】:
我正在尝试使用通用方法将所有下拉列表绑定到其各自的 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。当然,控件名称和类类型名称相同(“产品”),文本字段/值字段始终为“名称”。我认为它无法以正常方式实现,因为我无法从仅在运行时知道的类型创建编译时类型...也许使用反射或 Activator.CreateInstance?...
【问题讨论】:
-
你是什么意思“回到课堂”?类的新实例?
-
同意。杂乱的代码和糟糕的解释。我要编辑它,试图解释自己。基本上我只想在运行时获得符合上述条件的 DbSet
。
标签: c# asp.net entity-framework linq