Get SQL table name of an Entity in Entity Framework

29 August 2016   Comments   entity-framework sql

There are times when you find yourself needing to construct a raw SQL when working with Entity Framework. Particularly, if you want to stay away from the horror of hundreds-of-lines SQL generated by a complex EF mapping and would rather use Dapper to map the output of a raw SQL to your entities.

One of the dilemmas is to avoid hard-coding the table name, when the schema is all driven by EF. Well, here is the code you would need to get hold of the table name for a particular entity type:

public static string GetTableName(this ObjectContext context, Type t)
{
  var entityName = t.Name;
  var storageMetadata = context.MetadataWorkspace.GetItems<EntityContainerMapping>(DataSpace.CSSpace);

  foreach (var ecm in storageMetadata)
  {
      EntitySet entitySet;
      if (ecm.StoreEntityContainer.TryGetEntitySetByName(entityName, true, out entitySet))
      {
          return $"{entitySet.Schema}.[{entitySet.Table}]";
      }
  }

  return null;
}

blog comments powered by Disqus