I was found following code to find out the table name of an entity given entity class type using GetTableName
method. But GetEntitySet
method fails, because in TPH the table name, and therefore seemingly EntitySetBase is different than the subtype. It throws an exception with message "Entity type not found in GetTableName"
, from the throw
statement in line 15.
If I have a base class A
and a derived class B
, how can I find out which EntitySetBase object does type B correspond to? (It should give me EntitySetBase related to A, so that I can find out records are in table [dbo].[As]
.)
private static Dictionary<Type, EntitySetBase> _mappingCache =
new Dictionary<Type, EntitySetBase>();
private EntitySetBase GetEntitySet(Type type) {
if (!_mappingCache.ContainsKey(type)) {
ObjectContext octx = ((IObjectContextAdapter) this).ObjectContext;
string typeName = ObjectContext.GetObjectType(type).Name;
var es = octx.MetadataWorkspace
.GetItemCollection(DataSpace.SSpace)
.GetItems<EntityContainer>()
.SelectMany(c => c.BaseEntitySets
.Where(e => e.Name == typeName))
.FirstOrDefault();
if (es == null)
throw new ArgumentException("Entity type not found in GetTableName", typeName);
_mappingCache.Add(type, es);
}
return _mappingCache[type];
}
private string GetTableName(Type type) {
EntitySetBase es = GetEntitySet(type);
return string.Format("[{0}].[{1}]",
es.MetadataProperties["Schema"].Value,
es.MetadataProperties["Table"].Value);
}