【问题标题】:Get the class from the type itself从类型本身获取类
【发布时间】: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


【解决方案1】:

实体框架上下文具有按类型获取集合的方法,而不是直接访问 DbSet 属性

因此,您可以调用myDBEntity.Set(currentType)AsQueryable().ToList(),而不是myDBEntity.Products.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)

【讨论】:

  • 感谢您的回复。我试过了,但是 set(Type) 只返回一个 DbSet 而不是 DbSet,所以恐怕我们这里没有 ToList()。我错过了一个额外的步骤吗?
  • 它确实返回了一个类型 DbSet,你可能必须把 .AsQueryable(),我会更新答案
  • 你的意思是? myDBentity.Set(currentType).AsQueryable().ToListAsync()。我想你也忘记了一个点。无论如何,我用另一种解决方案重新编写了所有代码,现在正在工作。谢谢你的努力。
猜你喜欢
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 2020-01-29
  • 2011-01-25
相关资源
最近更新 更多