xaisoft
xaisoft

Reputation: 3451

Where clause in LINQ query is not recognized in vb.net?

The entity field is not recognized in the following Where clause. Is the VB wrong?

Dim projects = context.projects
               .OrderBy(Function(x) x.name)
               .Select(Function(x) {x.id, x.name})
               .Where(Function(x) x.id <> sourceid)

If I take the Where off, it works fine. Also, if I flip the Where and the OrderBy, Where is fine, but now OrderBy fails.

Upvotes: 3

Views: 2263

Answers (3)

Victor Zakharov
Victor Zakharov

Reputation: 26414

This {x.id, x.name} is most likely an array of object (assuming id is integer and name is string, VB would infer Object). It is not an instance of a class with properties of id and name. @shree.pat18 explained how it can be adjusted to return what you want, but I would suggest using query syntax for clarity, and also putting your where clause before Select (should be slightly faster, because it does not create anonymous objects from the values you don't need included in results):

Dim projects = From p In context.projects
               OrderBy p.name
               Where p.Id <> sourceid
               Select Id = p.Id, Name = p.Name

Upvotes: 0

shree.pat18
shree.pat18

Reputation: 21757

Try this:

Dim projects = context.projects
                               .OrderBy(Function(x) x.name)
                               .Select(Function(x) New With {x.id, x.name})
                               .Where(Function(x) x.id <> sourceid)

The New With keyword should create an IEnumerable of anonymous type. You can then work with the id property in the Where clause without having to change the order of your operations.

There is nothing stopping you from doing the operations OrderBy, Select, Where in that order. The above code will certainly compile and run. However, logically you need to do the Where before Select, since the former is a filtering operation, while the latter is a projection.

Upvotes: 3

Jayesh Goyani
Jayesh Goyani

Reputation: 11154

Can you please try with the below code snippet.

Dim projects = context.projects.Where(Function(x) x.id <> sourceid).OrderBy(Function(x) x.name).Select(Function(x) {x.id, x.name})

Upvotes: 2

Related Questions