开发者

Get Table Name From DbEntityEntry (Code-First)

开发者 https://www.devze.com 2023-03-18 06:10 出处:网络
Simple: How do I get the mapped table name from a DbEntityEntr开发者_运维问答y object? I\'m inside a class that extends DbContext. I\'ve seen examples for ObjectContext but doesn\'t apply to CF.

Simple: How do I get the mapped table name from a DbEntityEntr开发者_运维问答y object? I'm inside a class that extends DbContext. I've seen examples for ObjectContext but doesn't apply to CF.

Thanks.


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.


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;
}


Actually, you can get the ObjectContext from the DbContext (by casting it to IObjectContextAdapter) and use the examples you've seen.


On msdn you can find the documentation for DbContext, there you can see that it implements IObjectContextAdapter explicitly, so cast your DbContext-deriving Context to IObjectContextAdapter and use the ObjectContext property.

0

精彩评论

暂无评论...
验证码 换一张
取 消