在EF中,有没有办法做类似以下的事情?
'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
这当然是一个简单的例子,但其目的是将任何EF模型对象传递给函数,并在db.modelObjectType.Find(...)
调用中使用其类型。因此,例如,如果我传入customer
对象,它将从customer
表中检索。如果我传入address
对象,它将从地址表中检索。
答案 0 :(得分:1)
DbContext
类有一个非泛型方法(和通用版本,可能会提供更好的解决方案,具体取决于您调用此代码的方式)DbContext.Set
采用Type
要作为参数查询的实体。使用它,您的代码将是:
'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