按类型获取EntitySet以获取通用ById()扩展名 [英] Get EntitySet by type for a general-purpose ById() extension

查看:60
本文介绍了按类型获取EntitySet以获取通用ById()扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我通过id获取大量内容,这是一种简单的类型。因此,我决定将通用扩展T ById< T>(此ObjectQuery< T>查询,对象ID)用于代替FirstOrDefault(e => e.EntityId == id)。据我所知,我需要使用ObjectContext.GetObjectByKey()方法,所以我需要创建EntityKey。
如何为给定类型获取正确的实体集名称?或者也许有其他方法可以使用这种功能进行扩展?

In my app I'm getting tons of stuff by id, which is a simple type. So I decided to make a general-purpose extension T ById<T>(this ObjectQuery<T> query, object id)
to use it instead of FirstOrDefault(e => e.EntityId == id). As far as I understand, I need to use ObjectContext.GetObjectByKey() method, so I need to create EntityKey.
How can I get proper entity set name for a given type? Or maybe there's some other way to make an extension with this kind of functionality?

推荐答案

试试这个 - 这不是最快的方法,所以您可能希望为任何给定类型缓存此方法的结果。更好的方法是构建字典< Type,string>基于EntityContainer


Try this - it's not the fastest way to do it, so you probably want to cache results of this method for any given type. A better approach would be to build a dictionary<Type,string> based on EntityContainer

static EntitySet GetEntitySet(Type t, MetadataWorkspace workspace, string defaultContainerName)
{
    EdmEntityTypeAttribute eeta = (EdmEntityTypeAttribute)Attribute.GetCustomAttribute(t, typeof(EdmEntityTypeAttribute));

    string qualifiedName = eeta.NamespaceName + "." + eeta.Name;
    EntityType et = workspace.GetItem<EntityType>(qualifiedName, DataSpace.CSpace);

    EntityContainer ec = workspace.GetEntityContainer(defaultContainerName, DataSpace.CSpace);
    EntitySet foundSet = null;

    foreach (EntitySet set in ec.BaseEntitySets.OfType<EntitySet>())
    {
        if (et.IsKindOf(set.ElementType))
        {
            if (foundSet == null)
            {
                foundSet = set;
            }
            else
            {
                return null;
            }
        }
    }

   return foundSet;
}


这篇关于按类型获取EntitySet以获取通用ById()扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆