开发者

Entity Framework 4: Generic Repository: How do I determine the EntitySetName?

开发者 https://www.devze.com 2023-01-25 01:26 出处:网络
If y开发者_运维问答ou do a generic repository for an Entity in Entity Framework 4, you would start by querying the entity:

If y开发者_运维问答ou do a generic repository for an Entity in Entity Framework 4, you would start by querying the entity:

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

in that ... above we need the EntitySetName, which is usually the plural form of E's name. However, it's not always just as easy as adding an 's'. For example, this would work if we only just added an 's'.

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

This would contain our EntitySetName if we had a real entity:

E.EntityKey.EntitySetName

How can I get the EntitySetName when only provided the Type of E?


It's tricky, especially when proxies are involved, but possible. Here's how I do it in 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;
    }
0

精彩评论

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