2010-11-12 50 views
4

如果为实体实体做一个通用存储库Framework 4中,你会通过查询实体开始:实体框架4:通用存储库:如何确定EntitySetName?

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

...上面我们所需要的EntitySetName,这是通常的E的复数形式名称。但是,并不总是像添加's'一样简单。例如,如果我们只是添加了's',这将起作用。

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

这将包含我们的EntitySetName如果我们有一个真正的实体:

E.EntityKey.EntitySetName 

我怎样才能获得EntitySetName当仅供E的类型?

回答

6

这很棘手,特别是涉及代理时,但可能。以下是我如何在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; 
    } 
+1

这太神奇了。非常感谢你。那就是诀窍。 – 2010-11-13 03:28:13