Reputation: 3506
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.
Upvotes: 0
Views: 63
Reputation: 8150
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
Upvotes: 1