EntityFramework Get object by ID?

前端 未结 8 802
旧巷少年郎
旧巷少年郎 2020-12-23 20:48

Is it possible with Generics to get an object from my EntityFramework without knowing the type?

I\'m thinking of something along the lines of:

public         


        
8条回答
  •  渐次进展
    2020-12-23 21:38

    Here's the method I use to get an Entity object by ID.

    public TEntity GetByKey(object keyValue) where TEntity : class
        {            
            EntityKey key = GetEntityKey(keyValue);
    
            object originalItem;
            if (ObjectContext.TryGetObjectByKey(key, out originalItem))
            {
                return (TEntity)originalItem;
            }
            return default(TEntity);
        }
    

    You may find this a more robust solution than some of those provided above. I've used it as part of a generic repository in a lot of projects. Hope it helps you out.

提交回复
热议问题