Get the table name from the Entity Framework

c# ef-code-first entity entity-framework modelmetadata


I'm using the Code First method with Entity Framework 4.1. I can get the column names and storage model types for my entities:

var items = context.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.SSpace);

foreach (var i in items)
    Console.WriteLine("Table Name: {0}", i.Name);

    foreach (var key in i.KeyMembers)
        Console.WriteLine("\t{0} ({1})", key.Name, key.TypeUsage.EdmType.FullName);

    foreach (var member in i.Members)
        Console.WriteLine("\t{0} ({1})", member.Name, member.TypeUsage.EdmType.FullName);

The actual table name that the object is mapped to is what I need to know. That may be specified in a variety of ways using Fluent-API. DataAnnotation [TableAttribute], ToTable()).

Is there a typical technique to get this knowledge?

5/24/2011 7:08:10 AM

Popular Answer

Using Nigel's method (extracting the table name from the.ToTraceString() ) but with some changes, since his code won't function if the table isn't in the SQL Server default schema (dbo.{table-name} ).

I developed extension techniques forDbContext and ObjectContext objects:

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\s+(?<table>.+)\s+AS");
        Match match = regex.Match(sql);

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

Here are further details:
Get a mapped table name from an object using the entity framework

6/20/2016 1:31:28 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow