• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1094
  • Last Modified:

Calling a function within linq

I need to call a function within linq.

I have a linq to entities query:
                Return (From r In oEntities.aspnet_Roles _
                   Where _
                     Not _
                    (From t In oEntities.sssMenuRole _
                    Where _
                      CLng(t.menuId) = menuId2 _
                    Select t.RoleId).Contains(r.RoleId) _
                   Select _
                     r.RoleId, _
                     r.RoleName).ToList()

It receives this error:
LINQ to Entities does not recognize the method 'Boolean Contains[Int32](System.Linq.IQueryable`1[System.Int32], Int32)' method, and this method cannot be translated into a store expression.

In researching on google, I've found a workaround:
http://www.velocityreviews.com/forums/t645784-linq-where-clause.html

It is recommended to use a function such as this to build the contains expression:

    Public Shared Function BuildContainsExpression(Of TElement, TValue)( _
ByVal valueSelector As Expression(Of Func(Of TElement, TValue)), _
ByVal values As IEnumerable(Of TValue) _
) As Expression(Of Func(Of TElement, Boolean))

        ' validate arguments
        If IsNothing(valueSelector) Then Throw New ArgumentNullException("valueSelector")
        If IsNothing(values) Then Throw New ArgumentNullException("values")

        Dim p As ParameterExpression = valueSelector.Parameters.Single()
        If Not values.Any Then
            Return _
            Function(e) False
        End If

        Dim equals = values.Select( _
        Function(v) _
        Expression.Equal(valueSelector.Body, Expression.Constant(v, GetType(TValue))) _
        )

        Dim body = Equals.Aggregate( _
        Function(accumulate, equal) _
        Expression.Or(accumulate, equal) _
        )

        Return Expression.Lambda(Of Func(Of TElement, Boolean))(body, p)
    End Function

My problem is I can't figure out how to rewrite my query to use this method.

Please help?

thanks.
0
Starr Duskk
Asked:
Starr Duskk
1 Solution
 
dipakdave1983Commented:
calling function is pretty easy with linq/

1) create function into database
2) in VS from serverExplorer, drag function into your LINQ form/page/layout.

now to access it ,

FooBooDatacontext db = new FooBooDatacontext ();//your linq data context

db.yourfunction(param if exist);



0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now