Fetch by Primary Key using LINQ - Generic

In this blog we are going to see how we can fetch by Primary key using Linq and reflection.

The code for FetchByPrimaryKey is given as below :

   Public Function FetchByPrimaryKey(ByVal entity As TEntity, ByVal Value As String) Implements IService1.FetchByPrimaryKey
        Dim context As New DataEntities()


        Dim _objectSet As IEnumerable(Of TEntity) = GetObjectSet(entity)


        Dim Lambda As Func(Of TEntity, Boolean) = Function(e) e.Long_Name <> Value
        Dim o2 = _objectSet.Where(Lambda)
        Return o2.First()
    End Function


  Public Function GetObjectSet(ByVal entity As TEntity) As Object
        Dim context As New DataEntities()

        Dim typeArgs As Type() = {ObjectContext.GetObjectType(entity.[GetType]())}
        Dim typObjectContext As Type = context.[GetType]()
        Dim NoParams As Type() = {}
        Dim meth As MethodInfo = typObjectContext.GetMethod("CreateObjectSet", NoParams)
        Dim methGeneric As MethodInfo = meth.MakeGenericMethod(typeArgs)

        Return methGeneric.Invoke(context, Nothing)
    End Function