Looping through tables in Entity Framework 6

徘徊边缘 提交于 2020-01-16 06:28:49

问题


sorry for the simple question. I'm new at this. I have an entity model with several tables and I'd like to get a list of the tables, then I'd like to get the contents of a column from the tables.

For example, I have tables of subjects: Biology, Chemistry and Physics, each with a column className (among other columns). I'd like to loop through the tables, get the name then get the contents under that column since I need to ToList() it.

I want to do something like this:

for each (table in myEntityModel)
{
  Get tableName from table 
  Get contents under className from table 
}

I've tried using metadataworkspace, and I got a list of tableName, but that didn't help me too much in getting the contents of each table. I'm able to query individual tables, but I don't know how to change tables once I do. If I use: from r in myEntity.Biology select{...}, I can't change the entityset I'm referring to.

Oh, and, if the context of what I'm doing helps, I'm trying to build an accordion with the help of Ajax Control Toolkit 16.1 in Visual Studios 2015. I'm using Entity Framework 6.0. The subject name is going to be the headercontainer and the list of classes will be added as a gridview into the accordion pane. I'm new to C#, Visual Studios, databases, queries, entity models and almost everything I'm working with, but feel free to use as much jargon as you'd like. I'll google it if something confuses me. Thank you!


回答1:


It's not efficient, because it loads the entire table in memory, but you can do this:

 var myEntityModel = new MyEntityModel(); //your context

 var dbSets = myEntityModel.GetType().GetProperties().Where(p => p.PropertyType.Name.StartsWith("DbSet")); //get Dbset<T>

 foreach (var dbSetProps in dbSets)
 {
     var dbSet = dbSetProps.GetValue(myEntityModel, null);
     var dbSetType = dbSet.GetType().GetGenericArguments().First();

     var classNameProp = dbSetType.GetProperty("className");// i did not undestand, you want classes with className property?

     if (classNameProp != null)
     {
         var contents = ((IEnumerable) dbSet).Cast<object>().ToArray();//Get The Contents of table
     }


来源:https://stackoverflow.com/questions/36192805/looping-through-tables-in-entity-framework-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!