Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbSet table name

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

ObjectSetInstance.EntitySet.ToString()

Is there a way to do this on Entity Framework 4.1?

like image 814
Alexandre Avatar asked Jul 06 '11 15:07

Alexandre


People also ask

What does DbSet mean?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

What is DbSet and entity set?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.

What is DbSet attach?

Attach is used to repopulate a context with an entity that is known to already exist in the database. SaveChanges will therefore not attempt to insert an attached entity into the database because it is assumed to already be there.


2 Answers

Extension methods for DbContext and 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 a ObjectContext object:

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

Using a DbContext object:

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

More info here:

Entity Framework: Get mapped table name from an entity

like image 126
Rui Jarimba Avatar answered Sep 20 '22 05:09

Rui Jarimba


As of EF6.1, the solution explored in this article shows how to use the newly exposed metadata to accomplish this, should not require the database to be initialized or depend on what method was used to set the table name.

like image 34
Avi Cherry Avatar answered Sep 20 '22 05:09

Avi Cherry