代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

实体框架4:通用存储库:如何确定EntitySetName?

  •  4
  • Zachary Scott  · 技术社区  · 14 年前

    如果在实体框架4中为实体创建通用存储库,则首先查询该实体:

    public IEnumerable<E> GetEntity()
    {
        return _container.CreateQuery<E>( ... );
    }
    

    在那里面 ... 上面我们需要EntitySetName,它通常是 E 的名字。然而,这并不总是像添加“s”一样简单。例如,如果我们只添加一个“s”,这将起作用。

        return _container.CreateQuery<E>( "[" + typeof(E).Name + "s]");
    

    如果我们有一个真正的实体,那么它将包含EntitySetName:

    E.EntityKey.EntitySetName
    

    仅提供E类型时,如何获取EntitySetName?

    1 回复  |  直到 14 年前
        1
  •  6
  •   Craig Stuntz    14 年前

    这是棘手的,特别是当涉及代理,但可能的。我是这样做的 Halfpipe :

        /// <summary>
        /// Returns entity set name for a given entity type
        /// </summary>
        /// <param name="context">An ObjectContext which defines the entity set for entityType. Must be non-null.</param>
        /// <param name="entityType">An entity type. Must be non-null and have an entity set defined in the context argument.</param>
        /// <exception cref="ArgumentException">If entityType is not an entity or has no entity set defined in context.</exception>
        /// <returns>String name of the entity set.</returns>
        internal static string GetEntitySetName(this ObjectContext context, Type entityType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (entityType == null)
            {
                throw new ArgumentNullException("entityType");
            }
            // when POCO proxies are enabled, "entityType" may be a subtype of the mapped type.
            Type nonProxyEntityType = ObjectContext.GetObjectType(entityType);
            if (entityType == null)
            {
                throw new ArgumentException(
                    string.Format(System.Globalization.CultureInfo.CurrentUICulture,
                    Halfpipe.Resource.TypeIsNotAnEntity,
                    entityType.Name));
            }
    
            var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
            var result = (from entitySet in container.BaseEntitySets
                          where entitySet.ElementType.Name.Equals(nonProxyEntityType.Name)
                          select entitySet.Name).SingleOrDefault();
            if (string.IsNullOrEmpty(result))
            {
                throw new ArgumentException(
                    string.Format(System.Globalization.CultureInfo.CurrentUICulture,
                    Halfpipe.Resource.TypeIsNotAnEntity,
                    entityType.Name));
            }
            return result;
        }