This site runs best with JavaScript enabled.

Get table info for your entities in Entity Framework

Spencer Schneidenbach

January 07, 2016


I love Entity Framework.  It’s super useful and helps me be super productive.  However, in my heart I love SQL too and I don’t always like having so much of the database abstracted away from me.  To that end, I’ve had to Google for code on how to get table metadata for my Entity Framework entities on more than one occasion so that I could do some custom stuff like ETL.

Ok, so what do I mean by “table metadata”?  Table metadata consists of information about your entity as it relates to the SQL table that represents it, such as the name of the table, the names of any columns generated, etc.

In the past, I’ve used the EntityFramework.MappingAPI library on several occasions to provide this metadata.  However, the repo has not been maintained in nearly two years and there were a couple of show-stopping bugs that prevented me from using it.  So, I decided to fork the library and create my own: EntityFramework.Metadata.

Here’s a quick step-by-step on how to use it:

  1. Find a DbContext that contains tables you want to get metadata for.
  2. Call the .Db() extension method, passing in the type of the entity you want to get metadata for.
  3. Access all of the awesome information you need, such as TableName or SchemaName for information about the table.  Or go even further and get information about columns related to the properties of your entity.  The choices are endless!

And some quick sample code from the README:

static void Main()
{
    var context = new MyDbContext();
    var personData = context.Db<Person>(); 
    
    Console.WriteLine(personData.TableName); // output: People
    var nameColumn = personData.Prop("Name"); 
    Console.WriteLine(nameColumn.ColumnName); // output: MyName 
} 

[Table("People")]
public class Person
{
    public int PersonId { get; set; }
    [Column("MyName")]
    public string Name { get; set; }
}

View Code | Download via NuGet

Share article