EntityFramework Get object by ID?

前端 未结 8 648
旧巷少年郎
旧巷少年郎 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:30

    An other way to get entity from id on entitiy framework

    public T Get<T>(int id) where T : EntityObject;
    {
    var ObjectSet = _context.CreateObjectSet<T>();
    var PropName = ObjectSet.EntitySet.ElementType.KeyMembers[0].ToString();
    return  ObjectSet.Where("it." + PropName + "=" + id).FirstOrDefault();
    }
    

    Result

    SELECT TOP (1) 
    [Extent1].[CatId] AS [CatId], 
    [Extent1].[CatName] AS [CatName], 
    [Extent1].[CatType] AS [CatType],  
    FROM [dbo].[Categories] AS [Extent1]
    WHERE [Extent1].[CatId] = 1
    
    0 讨论(0)
  • 2020-12-23 21:33

    It's hard to make a completely generic solution because Entities can have composite keys, but this will work for a simple single key case.

    The key is to restrict T to be of type System.Data.Objects.DataClasses.EntityObject, which then has as EntityKey property (which represents the primary key).

    static T GetById<T>(object id) where T : EntityObject
    {
        using (var context = new MyEntities())
        {
            return context.CreateObjectSet<T>()
                .SingleOrDefault(t => t.EntityKey.EntityKeyValues[0].Value == id);
        }
    }
    
    0 讨论(0)
  • 2020-12-23 21:35

    I think this could help

    public static TEntity Find<TEntity>(this ObjectSet<TEntity> set, object id) where TEntity : EntityObject
        {
          using (var context = new MyObjectContext())
          {
            var entity = set.Context.CreateObjectSet<TEntity>();
            string keyName = entity.FirstOrDefault().EntityKey.EntityKeyValues.FirstOrDefault().Key;
    
            return entity.Where("it." + keyName + " = " + id).FirstOrDefault();
          }
        }
    
    0 讨论(0)
  • 2020-12-23 21:36

    You can define interface implemented by all your entities:

    public interface IEntity
    {
        int Id { get; }
    }
    

    and method to retrieve your entity:

    public T GetObjectById<T>(int id) where T : class, IEntity
    {
        return context.CreateObjectSet<T>().SingleOrDefault(e => e.Id == id);
    }
    

    You can also use similar approach to one provided in the linked question. You just have to use another method to get your entity:

    public virtual T GetByKey<T>(int id) where T : class, IEntity
    {
         string containerName = context.DefaultContainerName;
         string setName = context.CreateObjectSet<T>().EntitySet.Name;
         // Build entity key
         var entityKey = new EntityKey(containerName + "." + setName, "Id", id);
         return (TEntity)Context.GetObjectByKey(entityKey);         
    }
    

    The difference is that first method always query the database even if you have already loaded the instance to the context whereas second approach first checks if the instance is already loaded. The method is not so efficient because it builds these names over and over. Here is more general approach which can work with any key type and name and here is approach working with complex keys.

    Neither of this method directly works with inheritance - you must provide base type to make it work.

    0 讨论(0)
  • 2020-12-23 21:38

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

    public TEntity GetByKey<TEntity>(object keyValue) where TEntity : class
        {            
            EntityKey key = GetEntityKey<TEntity>(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.

    0 讨论(0)
  • 2020-12-23 21:43

    Finally solved the issue with this:
    http://pastebin.com/kjXUKBNS

    To call the code I use this:

    // Get the id of the object we are saving
    PropertyInfo prop = GetProperty<TEntity>(entity, entity.EntityKey.EntityKeyValues[0].Key);
    string entityID = prop.GetValue(entity, null).ToString();
    
    // Get the current version of this object
    var originalEntity = GetEntity<TEntity>(PropertyEquals, entityID);
    

    This makes the assumption that the Primary Key you are searching on is the first one in the list of Primary Keys.

    0 讨论(0)
提交回复
热议问题