0

In EF, is there a way to do something similar to the following?

'where obj is any EF model object in my context
Public Function GetSomeObject(obj as Object, id as long) as Object 
    Using db as ContextEntities = New ContextEntities
        Dim objType = obj.GetTypeOfObject()
        Dim someObject = db.objType.Find(id)
        'do magic from here on
        ....
    End Using
End Sub

This is, of course, a simple example but the idea is to pass in any EF model object to the function and use its type in the db.modelObjectType.Find(...) call. So, for example, if I pass in a customer object, it retrieves from the customer table. If I pass in an address object, it retrieves from the address table.

user4593252
  • 3,496
  • 6
  • 29
  • 55
  • 1
    Is `ContextEntities` a `DbContext`? If so, there are the generic and non-generic [`DbContext.Set`](https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.set%28v=vs.113%29.aspx) methods that may be what you are looking for... e.g. `Dim someObject = db.Set(obj.GetType()).Find(id)`. – Mark Jan 27 '16 at 20:05
  • Yes, it's a `DBContext`. I have found http://stackoverflow.com/questions/30675564/in-entity-framework-how-do-i-add-a-generic-entity-to-its-corresponding-dbset-wi which *might* be what I'm looking for. I'm testing it now. Edit: Your snippet seems to make the compiler happy. I'm going to test that too. – user4593252 Jan 27 '16 at 20:20
  • Mark, add your `db.set` code as an answer and I'll mark it as the correct answer. It works. – user4593252 Jan 27 '16 at 20:56

1 Answers1

1

The DbContext class has a non-generic method (and generic version, which may provide a better solution, depending on how you are calling this code) DbContext.Set that takes the Type of the entity to query as a parameter. Using this, your code would be:

'where obj is any EF model object in my context
Public Function GetSomeObject(obj as Object, id as long) as Object 
    Using db as ContextEntities = New ContextEntities
        Dim objType = obj.GetType()
        Dim someObject = db.Set(objType).Find(id)
        'do magic from here on
        ....
    End Using
End Sub
Mark
  • 8,140
  • 1
  • 14
  • 29