2

Thanks for looking.

I have a need to interrogate my entity class in order to get a list of all entities (tables) and, for each entity/table, I need a list of all foreign keys (navigation properties?) as well as a count of the records stored in that entity's corresponding data table.

So far, I have figured out how to get a list of all entities, but I am stuck as to how to get the foreign keys and record count for each. Any help is appreciated.

Here is my code so far:

 public static void GetAllEntities(SomeEntityContext db)
        {
            int trick = db.Some_Table.Count(); //The code below won't work without running some initial call against the entity context.  Not sure why.

            //Get a list of entities / tables
            IEnumerable<EntitySet> tables = db.MetadataWorkspace.GetItemCollection(DataSpace.SSpace)
                .GetItems<EntityContainer>()
                .Single()
                .BaseEntitySets
                .OfType<EntitySet>()
                .Where(s => !s.MetadataProperties.Contains("Type")
                            || s.MetadataProperties["Type"].ToString() == "Tables");

            foreach (var table in tables)
            {
                var tableName = table.MetadataProperties.Contains("Table")
                    && table.MetadataProperties["Table"].Value != null
                  ? table.MetadataProperties["Table"].Value.ToString()
                  : table.Name;

                //Print out some data
                System.Diagnostics.Debug.WriteLine(tableName);

                //ALSO NEED THE FOLLOWING:
                //--Count of records in table
                //--List of foreign keys for table

            }
        }
Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111

1 Answers1

0

Try creating a DbContext Extension as follows: e.g. http://weblogs.asp.net/ricardoperes/entity-framework-metadata

These methods should allow you to determine FKs from the TableNavigationColumns, etc.

  • GetTables
  • GetTableName
  • OneToMany
  • OneToOne
  • ManyToOne
  • ManyToMany
  • GetIdProperties
  • GetNavigationProperties
  • GetTableKeyColumns
  • GetTableColumns
  • GetTableNavigationColumns
Carl Prothman
  • 1,461
  • 13
  • 23