DbEntityEntry: Get Table Name (Code-First)

c# ef-code-first entity-framework

Question

Simple: From a DbEntityEntry object, how can I get the name of the mapped table? I'm within a DbContext-extending class. I've seen ObjectContext examples, but they don't applicable to CF.

Thanks.

1
2
7/6/2011 5:06:53 PM

Accepted Answer

The table name may be acquired using the IObjectContextAdapter, as was mentioned in another response.

 private string GetTableName(DbEntityEntry ent)
        {
            ObjectContext objectContext = ((IObjectContextAdapter) this).ObjectContext;
            Type entityType = ent.Entity.GetType();

            if (entityType.BaseType != null && entityType.Namespace == "System.Data.Entity.DynamicProxies")
                entityType = entityType.BaseType;

            string entityTypeName = entityType.Name;

            EntityContainer container =
                objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);
            string entitySetName = (from meta in container.BaseEntitySets
                                    where meta.ElementType.Name == entityTypeName
                                    select meta.Name).First();
            return entitySetName;
        }

The code mentioned above also checks for proxies. Assuming the original poster has found the solution long ago, I hope this helps everyone else who visits this page.

10
12/30/2013 7:15:32 PM

Popular Answer

At msdn, I discovered a cleaner method for getting rid of the proxy name.

private string GetTableName(DbEntityEntry ent)
{
     return ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
}


Related Questions





Related

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