通常检索Type的EF对象?

时间:2016-01-27 19:15:13

标签: vb.net entity-framework

在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对象,它将从地址表中检索。

1 个答案:

答案 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