DbSet table name

后端 未结 6 1199
广开言路
广开言路 2020-12-03 17:14

To get database table name on Entity framework 4.0 I do:

ObjectSetInstance.EntitySet.ToString()

Is there a way to do this on Entity Framewo

6条回答
  •  佛祖请我去吃肉
    2020-12-03 18:19

    Extension methods for DbContext and ObjectContext:

    public static class ContextExtensions
    {
        public static string GetTableName(this DbContext context) where T : class
        {
            ObjectContext objectContext = ((IObjectContextAdapter) context).ObjectContext;
    
            return objectContext.GetTableName();
        }
    
        public static string GetTableName(this ObjectContext context) where T : class
        {
            string sql = context.CreateObjectSet().ToTraceString();
            Regex regex = new Regex("FROM (?.*) AS");
            Match match = regex.Match(sql);
    
            string table = match.Groups["table"].Value;
            return table;
        }
    }
    

    Using a ObjectContext object:

    ObjectContext context = ....;
    string table = context.GetTableName();
    

    Using a DbContext object:

    DbContext context = ....;
    string table = context.GetTableName();
    

    More info here:

    Entity Framework: Get mapped table name from an entity

    提交回复
    热议问题