Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Entity Framework: Get mapped table name from an entity

, 19 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Extension methods for ObjectContext and DbContent to get the mapped table name from an entity.

Extension methods for ObjectContext and DbContent to get the mapped table name from an entity.

Table of contents

The problem

I am working on a set of extension methods to perform a bulk insert using Entity Framework, using internally the SqlBulkCopy object. One of the steps involved is to get the mapped table name from an entity. After some google searching, I found a post on StackOverflow that led me to the solution.

The solution

The trick is to use the method ObjectQuery.ToTraceString to generate a SQL Select statement for an entity, and then extract the table name from that statement.

Let’s assume that you have an entity named Album corresponding to a table named dbo.Albums.

// context is ObjectContext
string sql = context.CreateObjectSet<T>().ToTraceString();


The generated SQL for that entity can be something like this:

[Extent1].[AlbumId] AS [AlbumId], 
[Extent1].[GenreId] AS [GenreId], 
[Extent1].[ArtistId] AS [ArtistId], 
[Extent1].[Title] AS [Title], 
[Extent1].[Price] AS [Price], 
[Extent1].[AlbumArtUrl] AS [AlbumArtUrl]
FROM [dbo].[Albums] AS [Extent1]

So, all we need to do is to parse the SELECT statement to get the table name. This is the approach used in the post above but it has some limitations – that code will work only for tables that are in the default SQL Server schema (dbo.{tableName}). I made some changes to that code and I’m extracting the full table name using regular expressions.

The extension methods

I have created one extension method for DbContext and other for ObjectContext:

public static class ContextExtensions
    public static string GetTableName<T>(this DbContext context) where T : class
        ObjectContext objectContext = ((IObjectContextAdapter) context).ObjectContext;

        return objectContext.GetTableName<T>();

    public static string GetTableName<T>(this ObjectContext context) where T : class
        string sql = context.CreateObjectSet<T>().ToTraceString();
        Regex regex = new Regex("FROM (?<table>.*) AS");
        Match match = regex.Match(sql);

        string table = match.Groups["table"].Value;
        return table;

Using the code

Getting the mapped table name for an entity named Album, using a ObjectContext object:

ObjectContext context = ....;
string table = context.GetTableName<Album>();

Or using a DbContext object:

DbContext context = ....;
string table = context.GetTableName<Album>();



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Rui Jarimba
Software Developer (Senior)
Ireland Ireland
My name is Rui Jarimba and I was born in Madeira island, Portugal and I currently live in Dublin, Ireland.
I’m working as a .NET software developer since 2005.
Some of my professional interests are:
Web development using .NET Framework;
Service Oriented Architecture (SOA);
Database development and modelling;
Web accessibility, usability, and standards;
Software Architecture;
Design Patterns
Follow on   Twitter   LinkedIn

Comments and Discussions

QuestionExplanation of the Regex [modified] Pinmemberreggaeguitar5-Nov-14 12:29 
QuestionHow do I convert entity and property names (conceptual model) to table and column names (database store)? (Uses reflection.) PinmemberMember 1085265723-Jun-14 12:14 
QuestionThe same "alternative approach" in VB 2010 PinmemberMember 1085265729-May-14 7:30 
QuestionAn alternative approach PinmemberMember 368007811-Dec-12 2:35 
If you don't fancy parsing a SQL string,
    public string GetTableName<T>(DbContext context)
                where T: class
        var entitySet= GetEntitySet<T>(context);
        if (entitySet == null)
            throw new Exception("Unable to find entity set '{0}' in edm metadata".F(typeof(T).Name));
        var tableName = GetStringProperty(entitySet, "Schema") + "." + GetStringProperty(entitySet, "Table");
        return tableName;
    private EntitySet GetEntitySet<T>(DbContext context)
        var type = typeof(T);
        var entityName = type.Name;
        var metadata = ((IObjectContextAdapter)context).ObjectContext..MetadataWorkspace;
        IEnumerable<EntitySet> entitySets;
        entitySets = metadata.GetItemCollection(DataSpace.SSpace)
                         .Where(s => !s.MetadataProperties.Contains("Type")
                                     || s.MetadataProperties["Type"].ToString() == "Tables");
        var entitySet = entitySets.FirstOrDefault(t => t.Name == entityName);
        return entitySet;
    private string GetStringProperty(MetadataItem entitySet, string propertyName)
        MetadataProperty property;
        if (entitySet == null)
            throw new ArgumentNullException("entitySet");
        if (entitySet.MetadataProperties.TryGetValue(propertyName, false, out property))
            string str = null;
            if (((property != null) &&
                (property.Value != null)) &&
                (((str = property.Value as string) != null) &&
                return str;
        return string.Empty;
I'm using SqlBulCopy to do fast inserts, but getting the schema information from EF in a generic way.
This code is cobbled together from various places and tested it to the extent of my application requirements. The available code for using SqlBulkCopy in conjunction with EF seems a bit patchy, so hopefully this will assist anyone working in this area.
AnswerRe: An alternative approach PinmemberMember 1085265729-May-14 7:40 
SuggestionMake Oracle friendly PinmemberMark Johnston (SSCGP)26-Mar-12 10:46 
GeneralRe: Make Oracle friendly PinmemberRui Jarimba26-Mar-12 10:56 
SuggestionUpdate to include option for Schema in SQL Server PinmemberMark Johnston (SSCGP)26-Mar-12 10:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 19 Mar 2012
Article Copyright 2012 by Rui Jarimba
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid