EntityFramework Get object by ID?

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

    I think the Find() method may be able to do what you're looking for (DbSet.Find Method).

    var someEntity = dbSet.Find(keyValue);
    
    0 讨论(0)
  • 2020-12-23 21:48

    One thing I've done that has worked is to define a "KeyComparator" interface:

    public interface IHasKeyComparator<TObject> {
       Expression<Func<TObject, bool>> KeyComparator { get; } 
    }
    

    And then you can implement it on some object even with a multi-valued key:

    public sealed class MultiKeyedObject : IHasKeyComparator<MultiKeyedObject> {
       public int ID1 { get; set; }
       public string ID2 { get; set; }       
    
       readonly Expression<Func<MultiKeyedObject, bool>> mKeyComparator;
    
       public Expression<Func<MultiKeyedObject, bool>> KeyComparator {
          get { return mKeyComparator; }
       }
    
       public MultiKeyedObject() {
          mKeyComparator = other => other.ID1 == ID1 && other.ID2 == ID2;
       }
    }
    

    And can use it generically if you provide the constraint:

    public TObject Refresh<TObject>(TObject pObject)
    where TObject : IHasKeyComparator<TObject> {
       return this.Set<TObject>().Single(pObject.KeyComparator);
    }
    

    Doing it this way requires you to have an instance of the object, though, although you can fill an empty one with key values and then use it to pull from the DB.

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