DbEntityEntry: Get Table Name (Code-First)

c# ef-code-first entity-framework

Question

Simple: How do I get the mapped table name from a DbEntityEntry object? I'm inside a class that extends DbContext. I've seen examples for ObjectContext but doesn't apply to CF.

Thanks.

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

Accepted Answer

As stated in another answer, the table name can be obtained using the IObjectContextAdapter

 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 above code also tests for proxies. Hope this helps someone else who comes to this link as I assume the original poster solved this a long time ago.

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

Popular Answer

I found a cleaner way at msdn to get 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