Sandy
Sandy

Reputation: 11687

Loop through tables and columns of an Entity framework object

I have a database with name BookLibrary with 3 tables Author, Payroll and Article. I am using Entity framework to connect to database. I created a instance of it.

BookLibrary bookLibraryContext = new BookLibrary();

Now I want to cast this in a dataset (to pass dataset as a argument). How to do it?

Also by using T4 template I want to generate all column names as a readonly string property. And to do this, I need to loop through all tables and column names inside the database (and I want to do this through my entity object bookLibraryContext). But I am not sure how to loop through all tables and columns of an entity object? I have searched it on google but many suggested to use Reflection for looping or directly use SQL. I want to do it through C# and I am not much familiar with Reflection.

Upvotes: 2

Views: 7354

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

Now I want to cast this in a dataset (to pass dataset as a argument). How to do it?

Manually. EF and datasets are completely different technologies and neither of them contains any support for conversion to another. So you must manually create dataset and all data tables you want to use and manually fill them from the context.

If you want to work with datasets don't use Entity framework. Use dataset directly.

But I am not sure how to loop through all tables and columns of an entity object?

Entity object doesn't have this information. This information is hidden deep inside EF mapping which is available through bookLibraryContext.MetadataWorkspace. You don't need reflection to get this information. You just need to understand EDM and the way how it stores information.

Try something like this:

foreach (var entityType in context.MetadataWorkspace
                                  .GetItems<EntityType>(DataSpace.SSpace))
{
     string tableName = entityType.MetadataProperties
                                  .Single(m => m.Name == "Name")
                                  .Value
                                  .ToString();

     var members = (ReadOnlyMetadataCollection<EdmMember>)entityType
                                              .MetadataProperties
                                              .Single(m => m.Name == "Members")
                                              .Value;

     foreach (var columnName in members.Select(m => m.Name))
     {

     }
}

Upvotes: 2

Related Questions