すべてのドロップダウンリストをそれぞれのDBテーブルにSQLでバインドする汎用メソッドを試行しています(テスト目的のみ)。私は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);
}
}
私は、私は彼らが項目のリストを取得し、DDLでそれらを置くことができるように「製品」タイプを取得したいです。もちろん、コントロール名とクラスの型名は等しく(Product)、textfield/valueフィールドは常に「Name」です。私は実行時にのみ知られている型からコンパイル時の型を作成することができないため、通常の方法では達成できないと思います... ...
を呼び出すことができますが、「クラスを取り戻す」とは何を意味するのですか?クラスの新しいインスタンス? –
同意します。クラッターコードと不十分な説明。私はそれを編集して、自分自身を説明しようとしています。基本的には、実行時に上記の基準に一致するDbSetを取得したいだけです。 –