且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Entity Framework: Get mapped table name from an entity

更新时间:2022-10-04 17:33:25

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>();

 

原文 Entity Framework: Get mapped table name from an entity