Dynamic LINQ. No property or field 'FieldName' exists in type 'ClassName'

OrElse picture OrElse · Nov 15, 2011 · Viewed 7.1k times · Source

My LINQ query is as follows

Dim Query = From t In New XPQuery(Of xUser)(Xpo.Session.DefaultSession)
.Where("Name=John").Select("new (Name as FirstName)")

Unfortunately i get the error No property or field 'John' exists in type 'xUser'

Of course no such property exists in my xUser class, but hot can i fix that?

After reading within the DynamicLinq Class i found this function

Function FindPropertyOrField(ByVal type As Type, ByVal memberName As String, ByVal staticAccess As Boolean) As MemberInfo
    Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.DeclaredOnly Or _
        If(staticAccess, BindingFlags.Static, BindingFlags.Instance)
    For Each t As Type In SelfAndBaseTypes(Type)
        Dim members As MemberInfo() = t.FindMembers(MemberTypes.Property Or MemberTypes.Field, _
            flags, type.FilterNameIgnoreCase, memberName)
        If members.Length <> 0 Then Return members(0)
    Next
    Return Nothing
End Function

How can i edit my "faulty" query? What am i doing wrong here?

Thanks for your time.

Answer

Wouter de Kort picture Wouter de Kort · Nov 15, 2011

Try to set 'John' as a parameter instead of directly in the string.

Here you can find some documentation which shows this. It would look like .Where("Name=@0", "John")