可以通过实体的字符串名称加载实体吗?
我有以下示例代码,它从数据库中的表中获取值列表并将它们绑定到复选框列表。
var db = new DBContext();
db.Entity1.ToList().ForEach(
x => CheckBoxList1.Items.Add(new ListItem(x.Value, x.ID));
我有大约 10 个这样的复选框列表,我不想重复代码。我试图从中提取一个方法并将其用于所有复选框。是否可以通过字符串名称加载实体?类似 -
db.Load("Entity1").ToList().ForEach...
所以我可以传入实体名称和复选框列表,并在方法中执行 foreach 循环并绑定物品,像这样 -
void BindValues(string entityName, CheckBoxList checkBoxList)
{
db.Load("Entity1").ToList().ForEach(
x => checkBoxList.Items.Add(new ListItem(x.Value, x.ID)));
}
谢谢。
I have the following sample code which gets a list of values from a table in the DB and binds them to a checkbox list.
var db = new DBContext();
db.Entity1.ToList().ForEach(
x => CheckBoxList1.Items.Add(new ListItem(x.Value, x.ID));
I have about 10 checkboxlists like these and I dont want to repeat the code. I'm trying to extract a method out of it and use it for all checkboxes. Is it possible to load an entity by a string name? Something like -
db.Load("Entity1").ToList().ForEach...
So I can pass in the entity name and the checkbox list and do the foreach loop in the method and bind the items, like this -
void BindValues(string entityName, CheckBoxList checkBoxList)
{
db.Load("Entity1").ToList().ForEach(
x => checkBoxList.Items.Add(new ListItem(x.Value, x.ID)));
}
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Code First 中,DbContext 公开 .Set() 或 .Set(Type) 方法来获取表的句柄。因此,假设直接 EF 公开相同的内容,并且您很乐意通过实体类型而不是字符串来访问列表,那么这对您有用。
In Code First the DbContext exposes a .Set() or .Set(Type) method to get a handle on the table. So assuming straight EF exposes the same, and you are happy to access your lists by their entity type rather than a string, this would work for you.