Get Table Name From DbEntityEntry (Code-First)
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.
精彩评论