2017-02-23 83 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()。我想你也忘了一个点。无论如何,我用另一种解决方案重写了我的所有代码,现在正在开展工作。感谢你的努力。 –