如何在Table-Per-Hierarchy中找出实体类类型的表名?

时间:2014-04-28 00:54:25

标签: c# entity-framework table-per-hierarchy

我在代码后面找到了使用GetTableName方法查找给定实体类类型的实体的表名。但是GetEntitySet方法失败了,因为在TPH中表名,因此看似EntitySetBase与子类型不同。它从第15行的"Entity type not found in GetTableName"语句中抛出了消息throw的异常。

如果我有基类A和派生类B,我怎样才能找出B类对应的EntitySetBase对象? (它应该给我与A相关的EntitySetBase,以便我可以找到表[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);
    }

0 个答案:

没有答案