Zac*_*ott 4 c# reflection entity-framework-4
如果您为Entity Framework 4中的实体执行通用存储库,则首先要查询实体:
public IEnumerable<E> GetEntity()
{
return _container.CreateQuery<E>( ... );
}
Run Code Online (Sandbox Code Playgroud)
在...
上面我们需要EntitySetName,它通常是复数形式E
的名称.然而,它并不总是像添加's'一样容易.例如,如果我们只添加一个's',这将有效.
return _container.CreateQuery<E>( "[" + typeof(E).Name + "s]");
Run Code Online (Sandbox Code Playgroud)
如果我们有一个真实的实体,这将包含我们的EntitySetName:
E.EntityKey.EntitySetName
Run Code Online (Sandbox Code Playgroud)
当只提供E类型时,如何获取EntitySetName?
这很棘手,特别是涉及代理时,但可能.以下是我在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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1161 次 |
最近记录: |