从类型本身

时间:2017-02-23 22:19:18

标签: c# asp.net entity-framework linq

我正在尝试使用通用方法将所有下拉列表绑定到SQL中各自的DB表(仅用于测试目的)。我正在使用Entity框架。我几乎做了,但我认为我被困在一个不可能的任务(至少没有理想的),得到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);
    }
}

我希望得到产品&#39;键入,以便我可以获取项目列表并将它们放在ddl中。当然,控件名称和类类型名称相等(&#34; Product&#34;),textfield / valuefield总是&#34; Name&#34;。我认为无法以正常方式实现,因为我无法从仅在运行时知道的类型创建编译时类型...也许使用反射或Activator.CreateInstance?...

0 个答案:

没有答案