Looping through tables in Entity Framework 6

ajaxcontroltoolkit c# entity-framework entity-framework-6 visual-studio-2015


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!

3/24/2016 3:39:34 AM

Popular Answer

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
3/24/2016 5:59:55 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow